forked from rlkamradt/myfirstrepository
-
Notifications
You must be signed in to change notification settings - Fork 2
/
mongoservice.js
60 lines (51 loc) · 1.42 KB
/
mongoservice.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
const MongoClient = require('mongodb').MongoClient
const MONGO_USER = process.env.MONGO_USER
const MONGO_PASS = process.env.MONGO_PASS
const MONGO_SERVER = process.env.MONGO_SERVER || 'mongodb'
const MONGO_PORT = process.env.MONGO_PORT || 27017
const dbName = 'requests'
const mongourl = `mongodb://${MONGO_USER}:${MONGO_PASS}@${MONGO_SERVER}:${MONGO_PORT}`;
const client = new MongoClient(mongourl, {
useUnifiedTopology: true
})
module.exports.saveRequestAsync = async (req, res, next) => {
try {
const db = client.db(dbName)
const r = await db.collection('inserts').insertOne({
'verb': req.method,
'host': req.host,
'path': req.path
}, {
w: 'majority',
wtimeout: 10000,
serializeFunctions: true,
forceServerObjectId: true
}
)
console.log('Inserted')
} catch (err) {
console.log(err.stack)
}
next()
}
module.exports.addListToRequest = async (req,res,next) => {
try {
const db = client.db(dbName)
req.list = await db.collection('inserts').find({}).toArray();
if(!req.list) {
req.list = [ "empty" ]
}
} catch (err) {
console.log(err.stack)
}
next()
}
module.exports.initialize = async () => {
try {
console.log(`Connecting to mongodb://${MONGO_USER}:******@${MONGO_SERVER}:${MONGO_PORT}`)
await client.connect()
console.log('Connected correctly to server')
} catch (err) {
console.log(err.stack);
}
}