-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
executable file
·86 lines (68 loc) · 1.68 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const low = require('lowdb')
const uuid = require('uuid')
const fs = require('fs')
const defaultSettings = {
useId: false,
}
exports.create = (path, _settings) => {
const settings = Object.assign({}, defaultSettings, _settings)
if (path.lastIndexOf('/') > 1) {
const _path = path.slice(0, path.lastIndexOf('/'))
if (!fs.existsSync(_path)) {
fs.mkdirSync(_path)
}
}
const db = low(path)
db.defaults({ data: [] }).write()
const coll = db.get('data')
const push = item => {
if (settings.useId) {
item.id = uuid()
}
coll.push(item).write()
}
const insert = items => {
items.forEach(push)
}
const update = (target, item) => {
coll.find(target).assign(item).write()
}
const find = target => {
if(!target) return coll.value()
return coll.find(target).value()
}
const filter = target => {
return coll.filter(target).value()
}
const remove = target => {
coll.remove(target).write()
}
const upsert = (target, item) => {
if(!find(target)){
push(item)
} else {
update(target, item)
}
}
return { push, insert, update, find, filter, remove, upsert }
}
exports.createKeyValueStore = (path) => {
const db = low(path)
db.defaults({data: [{}]}).write()
const valueByKey = db.get('data').find({})
const get = () => {
return valueByKey.value()
}
const update = item => {
valueByKey.assign(item).write()
}
const set = item => {
const values = get()
const undefinedByKey = Object.keys(values).reduce((prev, key) => {
return Object.assign({}, prev, {[key]: undefined})
}, {})
update(undefinedByKey)
update(item)
}
return { get, update, set }
}