UNPKG

2.25 kBJavaScriptView Raw
1'use strict';
2const path = require('path');
3
4const ADAPTERS = require(path.join(__dirname, './adapters/index'));
5
6const CONTENT_ADAPTER_INTERFACE = class Adapter_Interface {
7 /**
8 * Creates an interface
9 * @param {Object} [options={}] A set of properties defined by keys with their allowed types as values. Each property will be required by newly constructed classes from this interface
10 */
11 constructor (options = {}) {
12 this.interface = (this.interface && typeof this.interface === 'object') ? this.interface : {};
13 for (let key in options) {
14 this.interface[key] = options[key];
15 }
16 }
17 /**
18 * Constructs a new object with a prototype defined by the .adapter ensuring that instantiated class conforms to interface requirements
19 * @param {Object} [options={}] Values to be passed to class constructor (.adapter should be reserved for either customer class or string that matches key in ADAPTERS)
20 * @param {string|Function} options.adapter Required to specify type of adapter to be constructed or a class constructor that can be instantiated with new keyword
21 * @param {string|Function} options.responder Alias for options.adapter. If options.responder is defined options.adapter will be ignored
22 * @return {Object} Returns an instantiated adapter class
23 */
24 create (options = {}) {
25 options.adapter = (options.responder) ? options.responder : options.adapter;
26 let Adapter = (typeof options.adapter === 'string') ? ADAPTERS[options.adapter] : options.adapter;
27 if (!Adapter) throw new Error('Could not find a corresponding adapter - for custom adapters pass the constructor as the "adapter" options');
28 let adapter = new Adapter(options);
29 let errors = [];
30 for (let key in this.interface) {
31 if (this.interface[key] !== typeof adapter[key]) errors.push(`${ key } is invalid type ${ typeof adapter[key] } and should be ${ this.interface[key] }`);
32 }
33 if (errors.length) {
34 let compiledErrors = errors.reduce((result, error, index) => {
35 if (index === errors.length - 1) result += error;
36 else result += `${ error }, `;
37 return result;
38 }, '');
39 throw new Error(compiledErrors);
40 }
41 return adapter;
42 }
43};
44
45module.exports = new CONTENT_ADAPTER_INTERFACE({
46 render: 'function',
47 error: 'function'
48});