Created
February 18, 2019 08:37
-
-
Save ioslh/2079da1c547dbe3e1321ab656c2cb5df to your computer and use it in GitHub Desktop.
Fake 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
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