rethinkts
Version:
A model system for RethinkDB, written in and for TypeScript.
91 lines • 3.21 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
exports.modelInfoKey = Symbol('rethink model info');
function createModelInfo(target, ...objs) {
return target[exports.modelInfoKey] = utils_1.assignWithArrays({
columns: [],
indexes: [],
relationships: [],
primaryKey: 'id',
tags: new Map(),
}, target[exports.modelInfoKey], ...objs);
}
exports.createModelInfo = createModelInfo;
/**
* Model decorator
*/
function Model(info) {
return (target) => {
const modelInfo = createModelInfo(target, info);
target.prototype.toJSON = function () {
return [...modelInfo.columns, ...modelInfo.relationships]
.filter(column => this[column.key] !== undefined)
.reduce((t, column) => (Object.assign({}, t, { [column.key]: this[column.key] })), {});
};
};
}
exports.Model = Model;
function getKeys(ctor, tagsOrKeys) {
const modelTags = Model.getInfo(ctor).tags;
let keys;
if (Array.isArray(tagsOrKeys)) {
keys = tagsOrKeys;
}
else {
keys = [tagsOrKeys];
}
return keys.reduce((keys, tagOrKey) => {
if (modelTags.has(tagOrKey)) {
return [...keys, ...modelTags.get(tagOrKey)];
}
return [...keys, tagOrKey];
}, []);
}
(function (Model) {
function construct(ctor, data) {
return Model.assign(new ctor(), data);
}
Model.construct = construct;
function assign(model, ...sources) {
return Object.assign(model, ...sources);
}
Model.assign = assign;
function pickAssign(model, tagsOrKeys, ...sources) {
const ctor = model.constructor;
const keys = getKeys(ctor, tagsOrKeys);
return Model.assign(model, ...sources.map(source => utils_1.pick(source, ...keys)));
}
Model.pickAssign = pickAssign;
function pick(model, ...tagsOrKeys) {
const ctor = model.constructor;
const modelTags = Model.getInfo(ctor).tags;
const data = tagsOrKeys.reduce((target, tagOrKey) => {
if (modelTags.has(tagOrKey)) {
return Object.assign({}, target, utils_1.pick(model, ...modelTags.get(tagOrKey)));
}
return Object.assign({}, target, { [tagOrKey]: model[tagOrKey] });
}, {});
return Model.construct(ctor, data);
}
Model.pick = pick;
function without(model, ...tagsOrKeys) {
const ctor = model.constructor;
const keys = getKeys(ctor, tagsOrKeys);
const pickKeys = Object.keys(model)
.filter(key => !keys.includes(key));
return Model.construct(ctor, utils_1.pick(model, ...pickKeys));
}
Model.without = without;
function getInfo(ctor) {
return ctor[exports.modelInfoKey];
}
Model.getInfo = getInfo;
function notify(model, hook, ...args) {
if (model[hook]) {
return model[hook](...args);
}
}
Model.notify = notify;
})(Model = exports.Model || (exports.Model = {}));
//# sourceMappingURL=model.js.map