-
Notifications
You must be signed in to change notification settings - Fork 2
/
db.js
65 lines (64 loc) · 1.33 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
const MongoClient = require("mongodb").MongoClient;
class DB{
constructor(config){
this.url = config.connectionstr || '';
this.getConnection();
this.initializeCounter();
}
_createConnection(){
return new Promise((resolve,reject)=>{
MongoClient.connect(this.url,function(err,db){
if(err){
reject(err);
return;
}
resolve(db);
});
});
}
getConnection(){
if(!this.db){
this.db=this._createConnection()
.catch((err)=>{
console.log("error creating connection:Err=>",err);
});
}
return this.db;
}
initializeCounter(){
this.counter={
node:0,
way:0,
relation:0
};
}
writeToMongo(dbname,data){
this.counter[dbname] += data.length;
return this.getConnection().then((db)=>{
return db.collection(dbname).insertMany(data);
})
}
clearDB(){
return this.getConnection().then((db)=>{
return Promise.all([
db.collection('node').drop(),
db.collection('way').drop(),
db.collection('relation').drop()
]);
})
.catch(()=>{
});
}
close(){
if(this.db){
this.db.then((db)=>{
console.log("closing connection");
this.db=null;
db.close();
});
}
}
}
exports.db = function(config){
return new DB(config);
}