const mongo = require('mongodb'); const MongoClient = mongo.MongoClient; const ObjectID = mongo.ObjectID; const DBName = "EMI_SOCIAL"; const mongoUrl = process.env.MONGO_URL; const postDB = require("./dbTools/post.js"); const profileDB = require("./dbTools/profile.js"); const getDB = new Promise((resolve, reject) => { const DB = {ObjectID: mongo.ObjectID}; MongoClient.connect(mongoUrl, function(err, db) { if (err) return reject(err); DB.db = db; DB.ObjectID = ObjectID; console.log("Connected to DB!"); DB.usersCol = db.db(DBName).collection("users"); DB.tokensCol = db.db(DBName).collection("tokens"); DB.checkSessionOnDB = async (session_id, user_sid)=>{ const temp_id = new mongo.ObjectID(session_id); //We can add cache, like a temporary Redis entry, to avoid calling the DB on each call const doc = await DB.tokensCol.findOne({"_id":temp_id}); if(doc && doc.uid == user_sid){ const userMongoId = new mongo.ObjectID(user_sid); const userInfo = await DB.usersCol.findOne({"_id": userMongoId}, {fields: {password: 0}}); return userInfo; } return false; }; DB.getUser = (username)=>{ return DB.usersCol.findOne({ username: username }); } DB.getUserById = (userid)=>{ const _id = new mongo.ObjectID(userid); return DB.usersCol.findOne({ _id }); } let usernamesCache = {} DB.getUsernameByIdCache = async (userid)=>{ if(usernamesCache[userid]) return usernamesCache[userid]; const _id = new mongo.ObjectID(userid); let user = await DB.usersCol.findOne({ _id }); usernamesCache[userid] = user.username; return usernamesCache[userid]; } DB.newUser = (userInformation)=>{ return DB.usersCol.insertOne(userInformation).catch((err)=>{ if (err.name === 'MongoError' && err.code === 11000) { // Duplicate username return "User already exists"; } console.log(err); return "System Error"; }); }; DB.newSession = (user_id)=>{ return DB.tokensCol.insertOne({uid: user_id}); } DB.removeSession = (session_id)=>{ const temp_id = new mongo.ObjectID(session_id); return DB.tokensCol.deleteOne({"_id":temp_id}); } postDB(DB); profileDB(DB); resolve(DB); }); }); exports.getDB = getDB;