loopback3: associate users to different databases - node.js

I'm developing a project in loopback3 where I need to create accounts for multiple companies, where each compnay has its own database, I'm fully aware that the loopback3 docs has a section where they explain how to create datasources programmatically and how to create models from that datasource, and I've used that to create the following code which receives in the request a parameter which i called dbname and this one changes the linking to the wanted datasource..
userclinic.js
Userclinic.observe('before save', async (ctx, next) => {
const dbname = ctx.instance.dbname; // database selection
const dbfound = await Userclinic.app.models.Clinics.findOne({where:{dbname}}) // checking if that database really exist in out registred clients databases
if( dbfound ){ // if database found
await connectToDatasource(dbname, Userclinic) // link the model to that database
} else { // otherwise
next(new Error('cancelled...')) // cancel the save
}
})
utils.js (from where i export my connectToDatasource method)
const connectToDatasource = (dbname, Model) => {
console.log("welcome");
var DataSource = require('loopback-datasource-juggler').DataSource;
var dataSource = new DataSource({
connector: require('loopback-connector-mongodb'),
host: 'localhost',
port: 27017,
database: dbname
});
Model.attachTo(dataSource);
}
module.exports = {
connectToDatasource
}
So my problem is that the datasource is actually really changing but the save happens in the previous datasource that was selected (which means it saves the instance to the old database) and doesn't save to the new one till I send the request again. so chaging the datasource is taking two requests to happen and it's also saving the instance in both databases.
I guess that when the request happen loopback checks the datasource related to that model first before allowing any action on that model, I really need to get this done by tonight and I wish someone can help out.
PS: if anyone has a solution to this or knows how to associate multiple clients (users) to multiple databases (programmatically of course) in any way using loopback 3 I'm all ears (eyes).
Thanks in advance.

Related

Database Connection using common module is not working [ mongoose and mongodb ]

I am trying to implement a common module for MongoDB connection using mongoose. and want to use the connection in other application for database operation. but facing issue when trying to use common database module. operation is halted / hanging after creating db connection. here is my codebase.
When I am using module specific dababase connection, then it is working fine, but when I am using common database connection it is hanging
Common DB Module
'use strict'
const mongoose = require('mongoose');
const DBOptions = require('./DBOption');
require("dotenv").config();
mongoose.Promise = global.Promise;
let isConnected;
const connectToDatabase = (MONGODB_URL) => {
if (isConnected) {
console.log('using existing database connection');
return Promise.resolve();
}
console.log('using new database connection');
console.log('DBOptions >> '+JSON.stringify(DBOptions));
return mongoose.connect(MONGODB_URL, DBOptions)
.then(db => {
console.log('db.connections[0].readyState >> '+db.connections[0].readyState);
isConnected = db.connections[0].readyState;
});
};
module.exports = connectToDatabase;
API Controller
const dbConnection = require('../DB/connection') // Internal Class
const DBConnection = require('as-common-util').connectToDatabase; // Common Class
/**
*
*/
app.get('/usr/alluser', async (req, res) => {
try {
//await dbConnection(process.env.MONGODB_URL) // This is working
await DBConnection(process.env.MONGODB_URL) // Code is hanging for this
let allUsers = await UserService.getAllUser()
console.log("All Users >> " + allUsers)
if (allUsers) {
return res.status(200).send(
new APIResponse({
success: true,
obj: allUsers
})
)
}
} catch (error) {
console.log(error)
}
})
It is hanging at following position
using new database connection
DBOptions >>
{"useNewUrlParser":true,"useUnifiedTopology":true,"useCreateIndex":true,"useFindAndModify":false,"autoIndex":false,"poolSize":10,"serverSelectionTimeoutMS":5000,"socketTimeoutMS":45000,"family":4}
db.connections[0].readyState >> 1
I am confused why same code is not working for common module.
This kind of pattern is not how Mongoose is meant to be used. Under the hood, Mongoose passes the underlying connection to the models in your module without the user really knowing anything about what is going on. That's why you can do magic stuff like MyModel.find() without ever having to create a model object yourself, or pass a db connection object to it.
If your db connection is in another module though, Mongoose won't be able to make those connections between your models and the MongoDB client connection since the models are no longer being registered on the mongoose object that is actually connected, and as a result, any requests you make using your models will break, since they will always be trying to connect through the object in your module.
There are other reasons why this won't, and shouldn't, work though. You're not supposed to be able to split a client. Doing so would make it unclear where communication along a client is coming from, or going to. You could change your function to make it return an established client connection. But your Mongoose models still wouldn't work. You would just be left with raw mongodb. If you want to do that, you might as well just uninstall Mongoose and use the mongodb library. Ultimately, you don't really gain anything from initializing the connection in a shared module. Initializing a connection is just a couple lines of code.
I doubt it's the connection that you want to share, rather it's the models (I'm guessing). You can put those in a shared module, and export them as a kind of connector function that injects the a given Mongoose instance into the models. See: Defining Mongoose Models in Separate Module.

Imported Sequelize connection works properly in one file but not another

I am writing a NodeJS API with express that uses Sequelize as an ORM to connect to a postgres database.
I have several API files containing the endpoint functions for each model, and I group related functions in these files.
In these files, I load the db connection by requiring the models folder, which contains all the model definitions, and an index file that instantiates & exports the database connection with the models.
I instantiate this at the top of any file that needs access to the database. My problem is that when I enter an endpoint, I can access the database connection perfectly. But when I call any function from another file that also accesses the database, all of my models from the required file are undefined, and it throws an error.
/* api/fooApi.js */
const db = require('../models')
const logApi = require('../logApi')
async function createFoo(req, res, next) {
try {
// db.foo and db.log are defined here, and accessible
const foo = await db.foo.create(req.body)
const log = await logApi.logCreation('foo', foo)
}
}
module.exports = { createFoo }
/* api/logApi.js */
const db = require('../models')
async function logCreation(recordType, record) {
// db.foo and db.log are not defined here when the function is called from fooApi.js
const log = await db.log.create({
event: 'create',
type: recordType,
details: `${recordType} record created by user ${record.createdBy}`
})
return log
}
module.exports = { logCreation }
When I enter the endpoint function createFoo(), I have full access to everything that I expect to be in db, including db.foo.create(). But in logCreation(), I cannot access these same functions.
Many different models will access the logCreation function, so it needs to be defined in one place. The require statement at the top of the file is exactly the same as that in fooApi, but when I debug the function, db is an empty object without any of the properties it should have.
If I pass db as an argument to logCreation, then the function works, but I'd like to avoid this if I can, as it would involve a major restructuring.
Previously to having thing set up this way, I had the following in each api file:
let db = null
function init (dbConn) {
db = dbConn
}
At setup, I would call init() in every API file using the same instance as the argument. However, this was a super clunky way of doing things that I wanted to move away from.
So my question is: What is the correct way to set up Sequelize so that I can access the database across multiple files?
I am using implicit transactions using namespace and cls-hooked as directed in the docs.
I solved my problem - this had nothing to do with how I was importing the file, and was entirely due to a circular dependency because a helper function on one of the models was accessing a helper function in an API file.

More than one Mongo endpoint in same API

My NodeJS application has form with text input field (for search) and a dropdown mongo for DEV, UAT and Production database options.
Based on the user selection respective database has to be accessed.
I want to know how to dynamically handle /change different database endpoint or change node env in run-time ?
One way that comes to my mind is to disconnect and connect again. If you are using mongoose, do something like:
var mongoose = require('mongoose')
...
try {
mongoose.disconnect();
mongoose.connect(mongoURL);
catch (e) {
console.log(e);
}
every time and take the mongoURL from the user input.
Another way is to use multiple connections:
var mongoose = require('mongoose')
var conn = mongoose.createConnection('mongodb://localhost/db1');
var conn2 = mongoose.createConnection('mongodb://localhost/db2');
and then choose the connection that you want to use depending on the user choice. I prefer this last one.
Take a look at this answer for more info:
https://stackoverflow.com/a/32909008/7041393

Sequelize: connect to database on run time based on the request

I am working on a node.js app where I need to connect to more than one databases. One of the database is central database which contains information common to all. And then there are country level databases where data is stored according to the countries.
I am using sequelize ORM in the app.
Database is postgresql.
Framework is express.
The problem is I want to decide on runtime based on the request which database to use and models should automatically connect to the appropriate database. I have seen this question but didn't found it helpful.
I have also checked in another forums but didn't find anything.
You need to create objects corresponding to each of your database, and at each this object you need to instantiate the Sequelize. Further, for each sequelize instance you need to import the models (assumming that all those databases have exactly the same tables and model representations).
import Sequelize from 'sequelize';
let connectionsArray = [
'postgres://user:pass#example.com:5432/country1',
'postgres://user:pass#example.com:5432/country2',
'postgres://user:pass#example.com:5432/country3',
];
let country1DB, country2DB, country3DB;
country1DB = country2DB = country3DB = {};
country1DB.Sequelize = country2DB.Sequelize = country3DB.Sequelize = Sequelize;
country1DB.sequelize = new Sequelize(connectionsArray[0]);
country2DB.sequelize = new Sequelize(connectionsArray[1]);
country3DB.sequelize = new Sequelize(connectionsArray[2]);
// here you need to access the models path, maybe with fs module
// iterate over every model and import it into every country sequelize instance
// let's assume that models' paths are in simple array
models.forEach(modelFile => {
let model1DB = country1DB.sequelize.import(modelFile);
let model2DB = country2DB.sequelize.import(modelFile);
let model3DB = country3DB.sequelize.import(modelFile);
country1DB[model1DB.name] = model1DB;
country2DB[model2DB.name] = model2DB;
country3DB[model3DB.name] = model3DB;
});
// now every country?DB object has it's own sequelize instance and all model definitions inside
export {
country1DB,
country2DB,
country3DB
};
This is just some example code, it would need refactor to be useful (introduce some loops etc.). It should just show you the idea of how to use multiple databases within single application. If you would like to use e.g. country1 database somewhere, you would simply do
import { country1DB } from './databases';
country1DB.User.findAll({...});
Above code would perform SELECT * FROM users in previously specified country1 database. Example express route could look like below:
import * as databases from './databases';
app.get('/:dbIndex/users', (req, res) => {
databases['country' + req.params.dbIndex + 'DB'].User.find().then(user => {
res.json(user.toJSON());
});
});
Or, even better, you could write some middleware function that would be run before every request and which would be responsible for choosing proper database for further operations.

efficiency of mongodb/mongoskin access by multiple modules approach?

I'm developing an express app that provides a REST api, it uses mongodb through mongoskin. I wanted a layer that splits routing from db acess. I have seen an example that creates a database bridge by creating a module file, an example models/profiles.js:
var mongo = require('mongoskin'),
db = mongo.db('localhost:27017/profiler'),
profs = db.collection('profiles');
exports.examplefunction = function (info, cb) {
//code that acess the profs collection and do the query
}
later this module is required in the routing files.
My question is: If I use this aproach for creating one module for each collection, will it be efficient? Do I have an issue of connecting and disconnecting multiple(unnecessary) times from mongo by doing that?
I was thiking that maybe exporting the db variable from one module to the others that handle each collection would solve the suposed issue, but I'm not sure.
Use a single connection and then create your modules passing in the shared db instance. You want to avoid setting up separate db pools for each module. One of doing this is to construct the module as a class.
exports.build = function(db) {
return new MyClass(db);
}
var MyClass = function(db) {
this.db = db;
}
MyClass.doQuery = function() {
}

Resources