blow-data
Version:
Data access layer for Blow.
120 lines (119 loc) • 5.21 kB
JavaScript
'use strict';
const util_1 = require('util');
const rxjs_1 = require('rxjs');
const blow_query_1 = require('blow-query');
const _ = require('./helpers');
class ModelRelationMetadata {
constructor(options) {
this._name = options.name;
this._type = options.type;
this._model = options.model;
this._foreignKey = options.foreignKey;
this._hidden = util_1.isUndefined(options.hidden) ? false : options.hidden;
}
get name() {
return this._name;
}
get type() {
return this._type;
}
get model() {
return this._model;
}
get foreignKey() {
return this._foreignKey;
}
get hidden() {
return this._hidden;
}
apply(model) {
switch (this.type) {
case 'belongsTo':
{
const relationName = this.name;
const targetModel = (_.getModel(this.model));
const targetKey = _.getModel(this.model).metadata.idProperty;
if (!model.metadata.hasProperty(this.foreignKey)) {
model.metadata.defineProperty({
name: this.foreignKey,
type: targetKey.type
});
}
const rootModel = model;
const rootKey = model.metadata.getProperty(this.foreignKey);
Object.defineProperty(model.prototype, relationName, {
enumerable: false,
configurable: false,
get: function () {
const inst = this;
return function (data) {
if (arguments.length > 0) {
inst[rootKey.name] = data[targetKey.name];
}
else {
if (inst[rootKey.name]) {
return targetModel.findById(inst[rootKey.name]);
}
else {
return rxjs_1.Observable.of(undefined);
}
}
};
}
});
}
break;
case 'hasMany':
{
const relationName = this.name;
const rootModel = model;
const rootKey = model.metadata.idProperty;
const targetMetadata = _.getModel(this.model).metadata;
if (!targetMetadata.hasProperty(this.foreignKey)) {
targetMetadata.defineProperty({
name: this.foreignKey,
type: rootKey.type
});
}
const targetModel = (_.getModel(this.model));
const targetKey = targetMetadata.getProperty(this.foreignKey);
Object.defineProperty(model.prototype, relationName, {
enumerable: false,
configurable: false,
get: function () {
const inst = this;
return {
create(data) {
data[targetKey.name] = inst[rootKey.name];
return targetModel.create(data);
},
find(query) {
const q = new blow_query_1.Query(query);
q.equal(targetKey.name, inst[rootKey.name]);
return targetModel.find(q);
},
findById(id) {
const q = new blow_query_1.Query();
q.equal(targetKey.name, inst[rootKey.name]);
q.equal(targetModel.metadata.idProperty.name, id);
return targetModel.findOne(q);
},
destroy(query) {
const q = new blow_query_1.Query({ where: query });
q.equal(targetKey.name, inst[rootKey.name]);
return targetModel.destroy(q.toJSON().where);
},
destroyById(id) {
const q = new blow_query_1.Query();
q.equal(targetModel.metadata.idProperty.name, id);
return this.destroy(q.toJSON().where);
}
};
}
});
}
break;
}
}
}
exports.ModelRelationMetadata = ModelRelationMetadata;