Files
kami-parse-server/src/Controllers/AdaptableController.js

71 lines
1.6 KiB
JavaScript
Raw Normal View History

/*
AdaptableController.js
AdaptableController is the base class for all controllers
2016-03-07 00:30:21 -08:00
that support adapter,
The super class takes care of creating the right instance for the adapter
based on the parameters passed
*/
// _adapter is private, use Symbol
var _adapter = Symbol();
import Config from '../Config';
export class AdaptableController {
constructor(adapter, appId, options) {
this.options = options;
this.appId = appId;
this.adapter = adapter;
}
set adapter(adapter) {
this.validateAdapter(adapter);
this[_adapter] = adapter;
}
2016-03-07 00:30:21 -08:00
get adapter() {
return this[_adapter];
}
2016-03-07 00:30:21 -08:00
get config() {
return new Config(this.appId);
}
2016-03-07 00:30:21 -08:00
expectedAdapterType() {
throw new Error("Subclasses should implement expectedAdapterType()");
2016-02-21 16:54:30 -05:00
}
2016-03-07 00:30:21 -08:00
validateAdapter(adapter) {
if (!adapter) {
throw new Error(this.constructor.name + " requires an adapter");
}
2016-03-07 00:30:21 -08:00
2016-12-07 15:17:05 -08:00
const Type = this.expectedAdapterType();
// Allow skipping for testing
2016-03-07 00:30:21 -08:00
if (!Type) {
return;
}
2016-03-07 00:30:21 -08:00
// Makes sure the prototype matches
2016-12-07 15:17:05 -08:00
const mismatches = Object.getOwnPropertyNames(Type.prototype).reduce((obj, key) => {
const adapterType = typeof adapter[key];
const expectedType = typeof Type.prototype[key];
if (adapterType !== expectedType) {
obj[key] = {
expected: expectedType,
actual: adapterType
}
}
return obj;
}, {});
2016-03-07 00:30:21 -08:00
if (Object.keys(mismatches).length > 0) {
throw new Error("Adapter prototype don't match expected prototype", adapter, mismatches);
}
2016-02-21 16:54:30 -05:00
}
}
2016-03-01 07:35:28 -08:00
export default AdaptableController;