This repository has been archived by the owner on Jul 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
123 lines (101 loc) · 2.62 KB
/
index.ts
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
121
122
123
import { MongoClient } from 'mongodb'
interface Config {
url: string
}
class InitMongo {
private client: MongoClient
private collection
private config: Config
constructor(config: Config) {
this.client = MongoClient
this.config = config
}
private caller(collectionName: string, callee: Function) {
return new Promise((resolve, reject) => {
this.client.connect(this.config.url, (err, db) => {
if (err) {
return reject(err)
}
this.collection = db.collection(collectionName)
return callee()
.then((data) => {
db.close()
resolve(data)
})
.catch(console.error)
})
})
}
/**
* Insert
*/
private insertCallee(elements: object[] | object) {
return new Promise((resolve, reject) => {
this.collection.insertMany(elements, (error, result) => {
if (error) {
return reject(error)
}
return resolve(result)
})
})
}
public insert(collectionName: string, elements: object[] | object) {
if (elements.constructor !== Array) {
elements = [elements]
}
return this.caller(collectionName, () => this.insertCallee(elements))
}
/**
* Find
*/
private findCallee(query: object) {
return new Promise((resolve, reject) => {
this.collection.find(query).toArray((error, result) => {
if (error) {
return reject(error)
}
return resolve(result)
});
})
}
public find(collectionName: string, query: object) {
return this.caller(collectionName, () => this.findCallee(query))
}
/**
* Delete
*/
private deleteCallee(elements: any) {
return new Promise((resolve, reject) => {
const element = elements[0]
this.collection.deleteOne({ id: element.id }, (error, result) => {
if (error) {
return reject(error)
}
return resolve(result)
})
})
}
public delete(collectionName: string, elements: object[] | object) {
if (elements.constructor !== Array) {
elements = [elements]
}
return this.caller(collectionName, () => this.deleteCallee(elements))
}
/**
* Update
*/
private updateCallee(element: any) {
return new Promise((resolve, reject) => {
this.collection.update({ id: element.id }, element, (error, result) => {
if (error) {
return reject(error)
}
return resolve(result)
})
})
}
public update(collectionName: string, element: object) {
return this.caller(collectionName, () => this.updateCallee(element))
}
}
export default InitMongo