59 lines
1.9 KiB
JavaScript
59 lines
1.9 KiB
JavaScript
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 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.newUser = (userInformation)=>{
|
|
console.log("NewUser", userInformation);
|
|
return DB.usersCol.insertOne(userInformation).catch((err)=>{
|
|
console.log(err);
|
|
return false;
|
|
});
|
|
};
|
|
|
|
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);
|
|
|
|
resolve(DB);
|
|
});
|
|
});
|
|
|
|
exports.getDB = getDB; |