/
index.js
120 lines (85 loc) · 2.47 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
116
117
118
119
120
import { applyOptions } from '../common'
import applyUpdate from '../../../common/apply_update'
import { inputRecord, outputRecord } from './helpers'
/**
* Memory adapter.
*/
export default Adapter => class MemoryAdapter extends Adapter {
connect () {
this.db = {}
const { recordTypes } = this
for (let type in recordTypes)
this.db[type] = {}
return Promise.resolve()
}
disconnect () {
delete this.db
return Promise.resolve()
}
find (type, ids, options = {}) {
if (ids && !ids.length) return super.find()
const { db, recordTypes } = this
const fields = recordTypes[type]
const collection = db[type]
let records = []
let count = 0
if (ids) for (let id of ids) {
const record = collection[id]
if (record) {
count++
records.push(outputRecord.call(this, type, record))
}
}
else for (let id in collection) {
count++
records.push(outputRecord.call(this, type, collection[id]))
}
return Promise.resolve(applyOptions(count, fields, records, options))
}
create (type, records) {
records = records.map(inputRecord.bind(this, type))
const { db, keys, errors: { ConflictError } } = this
const collection = db[type]
for (let record of records) {
const id = record[keys.primary]
if (id in collection)
return Promise.reject(new ConflictError(
`Record with ID "${id}" already exists.`))
}
for (let record of records) collection[record[keys.primary]] = record
return Promise.resolve(records.map(outputRecord.bind(this, type)))
}
update (type, updates) {
if (!updates.length) return super.update()
const { db, keys } = this
const collection = db[type]
let count = 0
for (let update of updates) {
const id = update[keys.primary]
let record = collection[id]
if (!record) continue
count++
record = outputRecord.call(this, type, record)
applyUpdate(record, update)
collection[id] = inputRecord.call(this, type, record)
}
return Promise.resolve(count)
}
delete (type, ids) {
if (ids && !ids.length) return super.delete()
const { db } = this
const collection = db[type]
let count = 0
if (ids) for (let id of ids) {
if (id in collection) {
count++
delete collection[id]
}
}
else for (let id in collection) {
count++
delete collection[id]
}
return Promise.resolve(count)
}
}