/**
* Data connection functions
*
* Provides quick access via functions to common data entities
*
* @author michael whobrey <mwhobrey@idealss.com>
*/
const { MongoClient } = require("mongodb");
const { constants } = require('./constants');
// const uri = "mongodb://" + (process.env.IDEAL_ENV === "production" ? "10.132.59.171" : "10.132.224.79") + ":27017/";
// const uri = "mongodb://127.0.0.1:27017/";
// const client = new MongoClient(uri);
/**
* Create a MongoClient.
*
* Create a mongo client connection in order to interact with mongo
*
* @param uri {string} the connection uri
*
* @return {MongoClient} client connection
*/
const createClient = async (uri) => {
console.log(`Connecting mongo client to ${uri}`);
const client = new MongoClient(uri);
return await client.connect();
}
/**
* Get the database name
*
* Return the correct database to use based the env var set
*
* @return {string} the database name
*/
const dbName = () => {
if (constants.isProduction()) {
return "api_admin_production";
}
else {
if (constants.isTesting()) {
// return "api_admin_development";
return "idealnet_testing";
}
else {
return "api_admin_development";
}
}
}
/**
* Lookup the auth doc tied to a token
*
* Lookup and return the auth doc tied to a provided token.
*
* @param {string} token - the identifying token of the client
* @param {MongoClient} dbClient - Client connection to use for auth doc access
*
* @return {Object} the auth doc for the token
*/
const authDoc = async (token, dbClient) => {
const aDatabase = dbClient.db(dbName());
const aCollection = aDatabase.collection('authorizations');
const aTCollection = aDatabase.collection('temp_authorizations');
let aDoc = await aCollection
.findOne({ _id: token });
if (aDoc === null) {
aDoc = await aTCollection
.findOne({ _id: token });
}
if (aDoc === null) {
aDoc = await aCollection.find();
console.log('No auth doc found for provided token: ', token);
return {};
}
return aDoc;
}
module.exports = {
authDoc,
createClient
}
module.exports.testingExports = {
authDoc,
dbName,
createClient
}