Skip to content

Commit

Permalink
certain model edit methods added
Browse files Browse the repository at this point in the history
  • Loading branch information
izelnakri committed Oct 22, 2017
1 parent abb15fa commit 98656e2
Showing 1 changed file with 43 additions and 3 deletions.
46 changes: 43 additions & 3 deletions lib/mem-server/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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] || [];
Expand All @@ -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) {
Expand Down

0 comments on commit 98656e2

Please sign in to comment.