@tsed/schema
Version:
JsonSchema module for Ts.ED Framework
84 lines (83 loc) • 2.17 kB
JavaScript
import { DecoratorTypes } from "@tsed/core";
import { pascalCase } from "change-case";
import { JsonEntityStore } from "./JsonEntityStore.js";
/**
* @ignore
*/
export class DecoratorContext extends Map {
constructor(opts = {}) {
super();
this.actions = [];
Object.entries(opts).forEach(([key, value]) => {
this.set(key, value);
});
}
addAction(cb) {
this.actions.push(cb);
return this;
}
build() {
const decorator = (...args) => this.bind(args, decorator);
const wrap = (cb) => {
return (...args) => {
cb(...args);
return decorator;
};
};
const wrapKey = (key) => {
return wrap((...values) => {
key in this ? this[key](...values) : this.set(key, values[0]);
});
};
this.methods.forEach((name) => {
decorator[pascalCase(name)] = wrapKey(name);
});
return decorator;
}
toObject() {
return [...this.entries()].reduce((obj, [key, value]) => {
return {
...obj,
[key]: value
};
}, {});
}
getMergedKey(key, defaultValue) {
let value = this.get(key) || defaultValue;
if (!value) {
return;
}
if (this.decoratorType === DecoratorTypes.CLASS) {
value = {
...value,
...(defaultValue || {})
};
}
return {
...(defaultValue || {}),
...value
};
}
bind(args, decorator) {
this.entity = JsonEntityStore.from(...args);
this.beforeInit();
this.onInit(args, decorator);
this.afterInit();
}
onInit(args, decorator) {
this.forEach((value, key) => {
this.onMapKey(key, value);
});
}
onMapKey(key, value) {
this.entity.set(key, value);
}
runActions() {
this.actions.forEach((action) => {
action(this);
});
return this;
}
beforeInit() { }
afterInit() { }
}