Last active
April 19, 2018 16:45
-
-
Save cklanac/f9c80fd1d5f55f5e96ea24bee7dd041f to your computer and use it in GitHub Desktop.
Simple In-Memory Database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
// Simple In-Memory Database (async-callback version) | |
const DELAY = 100; | |
const { promisify } = require('util'); | |
const simDB = { | |
// Synchronous Initialize | |
initialize: function (data) { | |
this.nextVal = 1000; | |
this.data = data.map(item => { | |
item.id = this.nextVal++; | |
return item; | |
}); | |
return this; | |
}, | |
// Asynchronous CRUD operations | |
create: function (newItem, callback) { | |
setTimeout(() => { | |
try { | |
newItem.id = this.nextVal++; | |
this.data.push(newItem); | |
callback(null, newItem); | |
} catch (err) { | |
callback(err); | |
} | |
}, DELAY); | |
}, | |
filter: function (term, callback) { | |
setTimeout(() => { | |
try { | |
let list = term ? this.data.filter(item => item.title.includes(term)) : this.data; | |
callback(null, list); | |
} catch (err) { | |
callback(err); | |
} | |
}, DELAY); | |
}, | |
find: function (id, callback) { | |
setTimeout(() => { | |
try { | |
id = Number(id); | |
let item = this.data.find(item => item.id === id); | |
callback(null, item); | |
} catch (err) { | |
callback(err); | |
} | |
}, DELAY); | |
}, | |
update: function (id, updateItem, callback) { | |
setTimeout(() => { | |
try { | |
id = Number(id); | |
let item = this.data.find(item => item.id === id); | |
if (!item) { | |
return callback(null, null); | |
} | |
Object.assign(item, updateItem); | |
callback(null, item); | |
} catch (err) { | |
callback(err); | |
} | |
}, DELAY); | |
}, | |
delete: function (id, callback) { | |
setTimeout(() => { | |
try { | |
id = Number(id); | |
const index = this.data.findIndex(item => item.id === id); | |
if (index === -1) { | |
return callback(null, null); | |
} else { | |
const len = this.data.splice(index, 1).length; | |
return callback(null, len); | |
} | |
} catch (err) { | |
callback(err); | |
} | |
}, DELAY); | |
} | |
}; | |
const simDB_Async = { | |
initialize: simDB.initialize, | |
create: promisify(simDB.create), | |
filter: promisify(simDB.filter), | |
find: promisify(simDB.find), | |
update: promisify(simDB.update), | |
delete: promisify(simDB.delete) | |
}; | |
module.exports = Object.create(simDB_Async); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment