huddle-record
Version:
Record is a Object-Relational Mapping (ORM) TypeScript plugin that makes it easy to work with data.
64 lines (63 loc) • 1.66 kB
JavaScript
export default class Model {
model;
id = -Math.floor(Math.random());
_created = false;
constructor(model, map) {
this.model = model;
this.beforeCreate(map);
setTimeout(() => {
this._created = true;
this.afterCreate(this);
}, 0);
}
save() {
// this could call the save() method on the api, allowing for direct calling of save() on an instance of a model
// instead of having to use the model class
return this.model.api.save();
}
setupRelation(model, data) {
// , key: string
if (data) {
// delete all existing relations
// (model.store as Repository<T>).query().where(key, this.id).delete();
// add new relations
model.store.transform(data, {
save: true,
replace: true,
prepend: false,
});
}
}
belongsTo(model, id) {
return id ? model.store.find(id) : null;
}
hasMany(model, key) {
return model.store.query().where(key, this.id).get();
}
has(key) {
const field = this[key];
return typeof field !== 'undefined' && typeof field !== null;
}
/*
* TODO: before & after events should be cancellable, so logic for creating/updating should be handled here
* instead of directly in the repository
*/
beforeCreate(map) {
//
}
afterCreate(instance) {
//
}
beforeDelete() {
//
}
afterDelete() {
//
}
beforeUpdate(map) {
//
}
afterUpdate(instance) {
//
}
}