-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
111 lines (92 loc) · 2 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
const ObjectID = require("mongodb").ObjectID;
const flatten = require("flat").flatten;
const merge = require("lodash.merge");
class CrudService {
constructor(mongoDB, collectionName) {
if (!mongoDB) {
throw new Error("mongoDB is required");
}
if (!collectionName) {
throw new Error("collectionName is required");
}
this.collection = mongoDB.collection(collectionName);
this.hasTimestamps = false;
}
marshal(x) {
return x;
}
create(props) {
var extraFields = this.hasTimestamps ? {
createdAt: new Date(),
updatedAt: new Date()
} : {};
return this.collection.insertOne(merge(extraFields, props))
.then(function(it) {
return it.ops[0];
})
.then(this.marshal);
}
list(filter) {
return this.collection.find(flatten(filter || {}))
.toArray()
.then(function(list) {
list.forEach(this.marshal);
return list;
}.bind(this));
}
show(id) {
return this.collection.findOne({_id: ObjectID(id)})
.then(function(x) {
if (!x) {
throw new Error("No such record found with ID: " + id);
}
return x;
})
.then(this.marshal);
}
update(id, modifications) {
var extraFields = this.hasTimestamps ? {
updatedAt: new Date()
} : {};
return this.collection.findOneAndUpdate(
{_id: ObjectID(id)},
{
$set: flatten(merge(extraFields, modifications), {safe: true})
},
{
upsert: false,
returnOriginal: false //return the modified body
}
)
.then(function(it) {
if (!it.value) {
throw new Error("no records found or updated");
}
return it.value;
})
.then(this.marshal);
}
remove(id) {
return this.collection.findOneAndDelete({_id: ObjectID(id)})
.then(function(it) {
if (!it.value) {
throw new Error("No documents deleted.");
}
return it.value;
})
.then(this.marshal);
}
setMarshaller(marshal) {
this.marshal = marshal;
return this;
}
enableTimestamps() {
this.hasTimestamps = true;
return this;
}
static idMarshaller(x) {
x.id = x._id;
return x;
}
}
module.exports = CrudService;