-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongodbapi.js
175 lines (140 loc) · 4.73 KB
/
mongodbapi.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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
const { MongoClient } = require('mongodb');
// Load environment variables from .env file
require('dotenv').config();
// Connection URI for MongoDB
var mongodbUri = 'mongodb://localhost:27017'
if (process.env.MONGODB_URI != undefined) {
mongodbUri = process.env.MONGODB_URI;
}
// Database name
const dbName = 'newsstack';
// Create a new MongoClient
const mongodbClient = new MongoClient(mongodbUri);
var mongodbconnected = false;
var userscollection = null;
connectMongoDB();
function isMongoDBConnected() {
return mongodbconnected;
}
async function connectMongoDB() {
try {
console.log("Trying to connect to MongoDB", mongodbUri, "..")
// Connect to the MongoDB server
await mongodbClient.connect();
// Get a reference to the "newsstack" database
const db = mongodbClient.db(dbName);
// Create a new "users" collection
userscollection = db.collection('users');
mongodbconnected = true;
console.log("Successfully connected to MongoDB", mongodbUri)
} catch (error) {
console.error("ERROR: Could not connect to MongoDB", mongodbUri, dbName, error)
mongodbconnected = false;
}
}
function closeMongoDBConnection() {
if (mongodbconnected){
// Close the client connection
mongodbClient.close();
mongodbconnected = false;
}
}
async function isUserExisting(sub) {
if (mongodbconnected) {
const result = await userscollection.findOne({ _id: sub })
if (result) {
console.log("isUserExisting: found user")
return true;
} else {
console.log("isUserExisting: did not find user")
return false;
}
}
}
async function createUser(sub, usr_data) {
if (mongodbconnected) {
const currentDate = new Date();
console.log("creating new user")
try {
// Insert a new document into the "users" collection
const result = await userscollection.insertOne({
_id: sub,
lastLogin: currentDate.toString(),
'user-data': usr_data,
'ns-data': null,
});
console.log(`Document created with ID ${result.insertedId}`);
} catch (err) {
console.error(err);
}
}
}
async function getNewsStacks(sub) {
if (mongodbconnected) {
const filter = { _id: sub };
const user = await userscollection.findOne(filter);
if (user) {
const ns_data = user['ns-data'];
return ns_data;
} else {
console.log('User with sub ' + sub + ' not found');
}
}
return null;
}
async function updateNewsStacks(sub, ns_data) {
if (mongodbconnected) {
const filter = { _id: sub };
const update = { $set: { 'ns-data': ns_data } };
const result = await userscollection.updateOne(filter, update);
if (result.modifiedCount === 1) {
console.log('ns-data field updated for user with sub ' + sub);
} else {
console.log('Error: User with sub ' + sub + ' not found');
}
}
}
async function getUserData(sub) {
if (mongodbconnected) {
const filter = { _id: sub };
const user = await userscollection.findOne(filter);
if (user) {
const user_data = user['user-data'];
return user_data;
} else {
console.log('User with sub ' + sub + ' not found');
}
}
return null;
}
async function updateUserData(sub, user_data) {
if (mongodbconnected) {
if (await isUserExisting(sub)) {
await createUser(sub, user_data);
}
else {
const filter = { _id: sub };
const update = { $set: { 'user-data': user_data } };
const result = await userscollection.updateOne(filter, update);
if (result.modifiedCount === 1) {
console.log('user-data field updated for user with sub ' + sub);
} else {
console.log('Error: User with sub ' + sub + ' not found');
}
}
}
}
async function updateLastLogin(sub) {
if (mongodbconnected) {
const currentDate = new Date();
const filter = { _id: sub };
const update = { $set: { lastLogin: currentDate.toString() } };
const result = await userscollection.updateOne(filter, update);
if (result.modifiedCount === 1) {
console.log('lastLogin field updated for user with sub ' + sub);
} else {
console.log('Error: User with sub ' + sub + ' not found');
}
}
}
module.exports = { updateUserData, updateNewsStacks, updateLastLogin, getNewsStacks, isUserExisting, createUser, getUserData };