i want solution for MYsql only
I want to switch database on per request bases i have achieved it in previous versions of sails but with this new version (1.0.0) i am not able to do sails.js - I want to add DB connection dynamically after sails lift
there is no documentation for it
i have primary database lets say DB_A which i use as default datastore to authenticate users after it users have their own database to interact and after lift it can be any database present in system with which user can connect and fetch
a few option i discovered
1) reload orm
2) create-manager
but dont know how to work with it as none of them are suggested
can any one help me with it
I was facing the similar issue while I was using PostgreSQL in sails app. I found a workaround below. ie npm install pg. in your case install mysql plugin ie npm i mysql
I have created dbconnections.js in the sails app controllers folder
const a = {
host: 'abc.com',
port: 'xxxx',
database: 'xxxx',
user: 'xxxx',
password: 'xxxx'
}
const b = {
host: 'ecd.com',
port: 'xxxx',
database: 'xxxx',
user: 'xxxx',
password: 'xxxx'
}
module.exports = { a: a, b: b};
then in my other controllers I have used pg plugin to match with the user passed db env through api
ie in my other controller
var sourceFile = require('./dbconnections.js');
const {
Client
} = require('pg');
for your case you could follow this https://www.npmjs.com/package/mysql to create connection object and follow the below logic to dynamically connect to different dbs
var match_env;
for (x in sourceFile) {
if (x === env) {
match_env = sourceFile[x];
}
}
const client = new Client(match_env)
now client object will have all postgresql transactions which one could execute, ie client.connect() const qry = "select * from person where city= "newyork"; client.query(qry, function (err, resp) {
console.log("before", client)
client.end();
console.log("after", client)
//user = JSON.parse(user);
if (err) {
return res.json({
error: err
});
}
if (resp === undefined) {
return res.notFound();
} else
console.log(resp);
return res.json({
userData: resp.rows
});
}
);
Based on the use case we could move the above code to other js file and call in as many controller as we can and this would work with multiple for multiple db connections of postgres sql in sails app.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.