UNPKG

test-data-store

Version:

an in-memory asynchronous promisified data-store simulator

65 lines (57 loc) 1.38 kB
module.exports = class Store { constructor() { this.data = []; this.id_stack = 0; } getAll() { return fakeAsync( () => { return this.data; }); } get(_id) { return fakeAsync( () => { const index = this.data.findIndex( u => u.id == _id); if (index >= 0) return this.data[index]; else return Promise.reject({status:500, id:_id}); }); } add(data) { return fakeAsync( () => { data['id'] = this.id_stack++; const index = this.data.push(data) - 1; return this.data[index]; }); } update(_id, data) { return fakeAsync( () => { const index = this.data.findIndex( u => u.id == _id); if (index > -1) { this.data[index] = data; return this.data[index]; } else { return Promise.reject({status:500, id:_d, data:data}); } }); } delete(_id) { return fakeAsync( () => { const index = this.data.findIndex( u => u.id == _id); if (index > -1) { const data = this.data.splice(index,1); return data[0]; } else { return Promise.reject({status:500, id: _id}); } }); } length() { return fakeAsync( () => { return this.data.length; }); } }; function fakeAsync(callback) { return new Promise((resolve) => { setTimeout( () => {resolve(callback());}, 50); }); };