This repository has been archived by the owner on Jun 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sql.js
55 lines (45 loc) · 1.37 KB
/
sql.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
const MongoClient = require("mongodb").MongoClient;
let cachedDb = null;
async function connectToDatabase(uri) {
if (cachedDb) return cachedDb;
const client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = await client.db("test");
cachedDb = db;
return db;
}
async function get_events() {
const db = await connectToDatabase(process.env.MONGODB_URI);
const collection = await db.collection("events");
return collection;
}
async function get_users() {
const db = await connectToDatabase(process.env.MONGODB_URI);
const collection = await db.collection("users");
return collection;
}
async function getUser(id) {
const users = await get_users();
return await users.findOne({ _id: id });;
}
async function getAllUsers() {
const users = await get_users();
return await users.find({}).toArray();
}
async function addUser(user) {
const users = await get_users();
return await users.insertOne(user);
}
async function updateUser(user) {
const users = await get_users();
return await users.replaceOne({ _id: user._id }, user);
}
async function logEvent(eventType, message) {
const events = await get_events();
await events.insertOne({ type: eventType, message: message, date: new Date() });
}
module.exports = {
connectToDatabase, get_users, getUser, getAllUsers, addUser, updateUser, logEvent
};