Skip to content

Instantly share code, notes, and snippets.

@ioslh
Created February 18, 2019 08:37
Show Gist options
  • Save ioslh/2079da1c547dbe3e1321ab656c2cb5df to your computer and use it in GitHub Desktop.
Save ioslh/2079da1c547dbe3e1321ab656c2cb5df to your computer and use it in GitHub Desktop.
Fake Database
const fs = require('fs')
class FakeDatabase {
constructor(dbPath) {
this._filePath = dbPath || './data.json'
this._data = JSON.parse(fs.readFileSync(this._filePath))
this._idBase = Math.max.apply(null, this._data.map(i => i.id))
}
_idGen() {
this._idBase += 1
return this._idBase
}
_sync() {
fs.writeFile(this._filePath, JSON.stringify(this._data))
}
create(payload) {
payload.id = this._idGen()
this._data.push(payload)
this._sync()
return payload
}
remove(id) {
let index = -1
this._data.find((item, idx) => {
if (item.id === id) {
index = idx
return true
}
})
if (index !== -1) {
this._data.splice(index, 1)
this._sync()
return {ok: 200}
}
return null
}
get(id) {
return this._data.find(item => item.id === id)
}
update(id, payload) {
const item = this.get(id)
if (!item) {
return null
}
for(const key in payload) {
if (key !== 'id') {
item[key] = payload[key]
}
}
this._sync()
return item
}
search(fields) {
const result = []
this._data.forEach(item => {
let isMatch = true
for(const key in fields) {
if (fields[key] !== item[key]) {
isMatch = false
break
}
}
if (isMatch) {
result.push(item)
}
})
return result
}
}
module.exports = FakeDatabase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment