-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
98 lines (96 loc) · 3.32 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
87
88
89
90
91
92
93
94
95
96
97
98
const path = require('path');
const config = require('./config');
const Database = require('tingodb')({}).Db;
class Db {
init(app, space, indexes) {
return new Promise((resolve, reject) => {
new Database(path.join(app.getPath('userData'), config.path.dir), {}).open((err, db) => {
if (err) {
console.error(err);
reject(err);
} else {
let collection = db.collection(space + '.db');
let i = 0;
if (i >= indexes.length) {
this.db = collection;
resolve(this);
} else {
const createIndex = () => {
let index = indexes[i];
let options = { };
if (!(index instanceof String) && typeof index !== 'string' && !(index instanceof Array)) {
options = index.options;
index = [index.key, typeof index.sort === 'undefined' ? 1 : index.sort];
}
collection.createIndex(index, options, err => {
if (err) {
console.error(err);
reject(err);
} else {
i++;
if (i >= indexes.length) {
this.db = collection;
resolve(this);
} else {
createIndex();
}
}
})
}
createIndex();
}
}
});
})
}
static async create(app, space, indexes) {
let db = new Db()
await db.init(app, space, indexes || []);
return db;
}
findOne(query, sortQuery) {
return new Promise((resolve, reject) => {
this.db.findOne(query, { sort: sortQuery }, (err, doc) => {
if (err) {
reject(err);
} else {
resolve(doc);
}
});
});
}
find(query, sortQuery) {
return new Promise((resolve, reject) => {
this.db.find(query, { sort: sortQuery }).toArray((err, docs) => {
if (err) {
reject(err);
} else {
resolve(docs);
}
})
});
}
insert(doc) {
return new Promise((resolve, reject) => {
this.db.insert(doc, {}, function(err) {
if (err) {
reject(err);
} else {
resolve(doc);
}
})
});
}
remove(query) {
return new Promise((resolve, reject) => {
this.db.remove(query, {}, function(err, docs) {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
});
}
}
module.exports = Db;