1.0.2 • Published 6 years ago
@canpy/composer v1.0.2
Composition over Inheritance using Mixins
Create a mixin class
module.exports = class Common {
unix_created_at() {
return moment(this.get('created_at')).unix()
}
unix_updated_at() {
return moment(this.get('updated_at')).unix()
}
static _mapping() {
return {
id: {
weight: -100,
or: [ 'null' ],
type: 'integer',
path: 'id'
},
created_at: {
weight: 100,
type: 'integer',
path: 'created_at',
get_method: 'unix_created_at'
},
updated_at: {
weight: 101,
type: 'integer',
path: 'updated_at',
get_method: 'unix_updated_at'
}
}
}
}
Create a resource class
const { composer, ResourceBase } = require('@canpy/composer');
class Resource extends ResourceBase {
// resource classes require a mixins static method
static mixins() {
return [
// add mixin names how ever you need, reference the callback below
'path/to/mixins/common.js',
'Common', // in micro-core we use Pasacal case paths
];
}
}
module.exports = composer(
Resource,
name => {
const path = // convert name to path. your needs define how this is done. ¯\_(ツ)_/¯
return require(path);
// in micro-core it would look something like this
return App.get(`Resources.Mixins.${name}`);
}
);
Now use that composed class. 🎉
const Resource = require('path/to/resource/class');
Resource.mapping
const resource = new Resource({
id: 32,
created_at: 'now',
updated_at: 'now'
});
resource.toJSON();
resource.get('id');
Mixins more details
module.exports = class MixinExample {
// Define any static or instance methods that should be added to the
// resource class.
// optional methods that can be defined in your mixin class
static _mapping() {
// redefine in your mixin class
// Example Property Definition
return {
prop_name: {
type: 'enum[text, integer, double, boolean]',
or: 'array of valid scheam property types',
// optional
schema_ignore: 'boolean, should this property be rendered in the validation schema and the toJSON',
weight: 'integer determining the order in wich the property should fall',
get_method: 'string of the instance function that should be called inside the getter'
// any jsonschema property http://json-schema.org/examples.html
}
}
}
static mixinSetup(resource) {
// redefine in your mixin class
}
static mixinPreProcessSetProperty(resource, prop, new_value) {
// redefine in your mixin class
}
static mixinPostProcessSetProperty(resource, prop) {
// redefine in your mixin class
}
}