UNPKG

blow-data

Version:
71 lines (70 loc) 2.34 kB
'use strict'; const BaseModel_1 = require('./BaseModel'); const helpers = require('./helpers'); class PersistedModel extends BaseModel_1.BaseModel { destroy() { return helpers.getCtor(this) .destroyById(helpers.getIdValue(this)); } save() { return helpers.getCtor(this) .updateOrCreate(this).map(saved => this.merge(saved.toJSON ? saved.toJSON() : saved)); } refresh() { return helpers.getCtor(this) .findById(helpers.getIdValue(this)) .map(refreshed => this.merge(refreshed.toJSON ? refreshed.toJSON() : refreshed)); } static _prepareSave(data) { if (data instanceof PersistedModel) { return data.toJSON(); } return data; } static init(data) { return new this(data); } static count(where) { return this.adapter.count(this.metadata, where); } static create(data) { return this.adapter.create(this.metadata, this._prepareSave(data)) .map(result => this.init(result)); } static destroy(where) { return this.adapter.destroy(this.metadata, where); } static destroyById(id) { return this.adapter.destroyById(this.metadata, id); } static exists(id) { return this.adapter.exists(this.metadata, id); } static find(query) { return this.adapter.find(this.metadata, query) .map(result => this.init(result)); } static findOne(query) { return this.adapter.findOne(this.metadata, query) .map(result => this.init(result)); } static findById(id) { return this.adapter.findById(this.metadata, id) .map(result => this.init(result)); } static findOrCreate(where, data) { return this.adapter.findOrCreate(this.metadata, where, this._prepareSave(data)) .map(result => this.init(result)); } static update(where, data) { return this.adapter.update(this.metadata, where, this._prepareSave(data)); } static updateOrCreate(data) { return this.adapter.updateOrCreate(this.metadata, this._prepareSave(data)) .map(result => this.init(result)); } static get adapter() { return this.connection.adapter; } } exports.PersistedModel = PersistedModel;