From 98656e2c75175ad85dc068e8251d3bd9693ba36f Mon Sep 17 00:00:00 2001 From: Izel Nakri Date: Sun, 22 Oct 2017 20:35:49 +0200 Subject: [PATCH] certain model edit methods added --- lib/mem-server/model.js | 46 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/lib/mem-server/model.js b/lib/mem-server/model.js index 3451ecc..73e111a 100644 --- a/lib/mem-server/model.js +++ b/lib/mem-server/model.js @@ -3,12 +3,22 @@ const targetNamespace = ENVIRONMENT_IS_NODE ? global : window; export default { modelName: '', - insert(options) { - // const attributes = Object.keys(this); + attributes: [], + insert(options) { // NOTE: what if there is same id? + const models = targetNamespace.MemServer.DB[this.modelName] || []; + + // TODO: auto-increment ids + const defaultAttributes = this.attributes.reduce((result, attribute) => { + // TODO: enable functions + result[attribute] = this[attribute]; + }, {}); + + const targetAttributes = Object.assign(defaultAttributes, options); + models.push(targetAttributes); }, bulkInsert(count, options) { - + return Array.from({ length: count }).map(() => this.insert(options)); }, find(id) { const models = targetNamespace.MemServer.DB[this.modelName] || []; @@ -33,9 +43,39 @@ export default { return models.find((model) => comparison(model, options, keys, 0)); }, update(record) { + const targetRecord = record.id ? this.find(record.id) : this.findBy({ uuid: record.uuid }); + + if (!targetRecord) { + throw new Error('[MemServer] $Model.update(record) requires id or uuid primary key to update a record'); + } + + const targetIndex = models.indexOf(targetRecord); + + targetNamespace.MemServer.DB[this.modelName][targetIndex] = Object.assign(targetRecord, record); + + return targetNamespace.MemServer.DB[this.modelName][targetIndex]; + }, + bulkUpdate() { }, destroy(record) { + const models = targetNamespace.MemServer.DB[this.modelName]; + + if (models.length === 0) { + throw new Error(`[MemServer] ${this.modelName} has no records in the database to remove`); + } + + const targetRecord = record.id ? this.find(record.id) : this.findBy({ uuid: record.uuid }); + + if (!targetRecord) { + throw new Error('[MemServer] $Model.destroy(record) requires id or uuid primary key to destroy a record'); + } + + const targetIndex = models.indexOf(targetRecord); + + targetNamespace.MemServer.DB[this.modelName] = models.splice(targetIndex, 1); + }, + bulkDestroy() { }, serialize(objectOrArray) {