forked from typicode/lowdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
115 lines (96 loc) · 2.66 KB
/
index.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const test = require('tape')
const sinon = require('sinon')
const low = require('../src/index.node')
const _test = (str, { source, read, write, promise, writeOnChange } = {}) => {
test(str, async function (t) {
try {
let db
let count
if (source) {
if (writeOnChange) {
// Test that writeOnChange is true by default
db = promise
? await low(source, { storage: { read, write }})
: low(source, { storage: { read, write }})
} else {
db = promise
? await low(source, { storage: { read, write }, writeOnChange })
: low(source, { storage: { read, write }, writeOnChange })
}
} else {
db = low()
}
db.defaults({
users: []
}).value()
let users = db.get('users')
// db('').value() should always return a value (Fix #82)
if (promise) t.deepEqual(users.value(), [])
// Add user
let [ foo ] = users.push('foo').value()
t.is(foo, 'foo')
t.is(users.value().length, 1, 'should add user')
if (write) {
count = writeOnChange ? 2 : 0
t.is(write.callCount, count, 'should auto write')
}
if (write) {
db.setState({})
// Should automatically write new state
count = writeOnChange ? 3 : 0
t.is(write.callCount, count, 'should auto write after setState()')
// write dest
promise
? await db.write('backup.json')
: db.write('backup.json')
// get last write call
let args = write.args.slice(-1)[0]
t.same(args, ['backup.json', {}, undefined], 'should write to backup.json')
}
if (read) {
// read
promise
? await db.read()
: db.read()
t.is(read.callCount, 2)
promise
? await db.read('backup.json')
: db.read('backup.json')
let args = read.args.slice(-1)[0]
t.same(args, ['backup.json', undefined], 'should read from backup.json')
}
t.end()
} catch (err) {
t.end(err)
}
})
}
_test('in-memory')
_test('sync', {
source: 'db.json',
read: sinon.spy(() => ({})),
write: sinon.spy(),
writeOnChange: true
})
_test('promises', {
source: 'db.json',
read: sinon.spy(() => Promise.resolve({})),
write: sinon.spy(() => Promise.resolve()),
promise: true,
writeOnChange: true
})
_test('read-only', {
source: 'db.json',
read: sinon.spy(() => ({})),
writeOnChange: true
})
_test('write-only', {
source: 'db.json',
write: sinon.spy(),
writeOnChange: true
})
_test('writeOnChange = false', {
source: 'db.json',
write: sinon.spy(),
writeOnChange: false
})