Javascript 如何根据每个客户端动态连接mysql数据库?
我正在使用MEAN stack here M=mysql构建一个SaaS产品 我正在使用sequelize作为mysql的ORM,我的连接:Javascript 如何根据每个客户端动态连接mysql数据库?,javascript,mysql,node.js,sequelize.js,saas,Javascript,Mysql,Node.js,Sequelize.js,Saas,我正在使用MEAN stack here M=mysql构建一个SaaS产品 我正在使用sequelize作为mysql的ORM,我的连接: const sequelize = new Sequelize('smallscale_superapp', 'root', 'root1', { host: '127.0.0.1', port: 3306, dialect: 'mysql', logging: false, }); 例如,我有一个管理超级应用程序,所以我创建了一个业务,
const sequelize = new Sequelize('smallscale_superapp', 'root', 'root1', {
host: '127.0.0.1',
port: 3306,
dialect: 'mysql',
logging: false,
});
例如,我有一个管理超级应用程序,所以我创建了一个业务,例如业务代码
“001abcd”,这个业务代码存储在我的主管理数据库中,然后我告诉我的所有客户转到一个名为“example.com”的特定url
因此,如果他们输入url,主页将看起来像slack.com。有一个输入框,在硬编码值example.com之后
现在,我的客户机在输入框中输入了我创建的业务代码,并存储在我的主数据库中
将业务代码放入输入框后,将打开一个名为“001abcd.example.com”的新子域(如果匹配,我将在创建动态子域时检查主数据库中的业务代码是否匹配)
所以,如果一切正常,子域客户端页面创建后将显示为登录屏幕,在那里他们需要注册,注册详细信息需要在那里动态显示
注意:在创建业务时,我在主数据库表中获取客户端数据库、用户名、主机和密码
如何使用sequelize mysql实现这一点
如何让sequelize连接基于客户端登录动态连接
正如我之前所说,我的数据库中有客户机dbname..etc,我正在尝试创建如下连接:
exports.dynamicDatabase = (req, res) => {
const { code } = req.params;
Business.find({
where: { code },
raw: true,
})
.then((data) => {
const sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {
host: data.dbhost,
port: 3306,
dialect: 'mysql',
logging: false,
});
})
.catch((err) => { res.status(400).send(err.message); });
};
sequelizeClient.authenticate().then((err) => {
if (err) {
console.log('There is connection in ERROR.');
} else {
console.log('Dynamic MYSQL Connection has been established successfully');
}
});
sequelizeClient.sync().then(() => {
console.log('Dynamic Missing Table Created');
}, (err) => {
console.log('An error occurred while creating the table:', err.message);
});
现在,在我的这个函数之外,我正在尝试同步表,如下所示:
exports.dynamicDatabase = (req, res) => {
const { code } = req.params;
Business.find({
where: { code },
raw: true,
})
.then((data) => {
const sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {
host: data.dbhost,
port: 3306,
dialect: 'mysql',
logging: false,
});
})
.catch((err) => { res.status(400).send(err.message); });
};
sequelizeClient.authenticate().then((err) => {
if (err) {
console.log('There is connection in ERROR.');
} else {
console.log('Dynamic MYSQL Connection has been established successfully');
}
});
sequelizeClient.sync().then(() => {
console.log('Dynamic Missing Table Created');
}, (err) => {
console.log('An error occurred while creating the table:', err.message);
});
变量sequelizeClient位于函数内部,因此我无法访问?全球范围内
所以我把变量设为全局变量,但有一个问题
我在函数中有sequelizeClient变量,该函数只在url中输入我的域后执行
但是sequelizeClient.sync()不在函数中,因此当我启动node server.js时,它会抛出错误:
sequelizeClient.authenticate().then((err) => {
[0] ^
[0]
[0] TypeError: Cannot read property 'authenticate' of undefined
最后,我尝试了这个方法并使其发挥作用,但我不知道这是一个好方法还是不好,所以请告诉我这是否是一个好方法 我通过用户请求参数获取准确数据:
let sequelizeClient;
let Login;
exports.getDomain = (req, res) => {
const { code } = req.params;
Business.find({
raw: true,
where: { code },
}).then((data) => {
if (data === null) {
res.status(400).send(data);
} else {
sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {
host: data.dbhost,
port: 3306,
dialect: 'mysql',
logging: false,
});
// end user connections
sequelizeClient.authenticate().then((err) => {
if (err) {
console.log('There is connection in ERROR.');
} else {
console.log(`${data.code} MYSQL Connection has been established successfully`);
}
});
sequelizeClient.sync().then(() => {
console.log(`${data.code} Missing Table Created`);
}, (err) => {
console.log('An error occurred while creating the table:', err.message);
});
// mysql tables;
Login = sequelizeClient.define('login', {
username: Sequelize.STRING,
firstName: Sequelize.STRING,
lastName: Sequelize.STRING,
});
}
});
};
我将表模式变量声明为全局变量,并在代码中使用:
// api
exports.signUp = (req, res) => {
const user = {
username: req.body.username,
firstName: req.body.firstName,
lastName: req.body.lastName,
};
Login.create(user)
.then(data => res.status(200).send(data))
.catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))
.catch(err => res.status(400).send(err.message));
};
是的,经过大量搜索,我发现有三种数据库方法可以构建SaaS产品
const postgresDB = new Sequelize('postgres://localhost:5432/test_enduser');
postgresDB.authenticate().then((err) => {
if (err) {
console.log('There is connection in ERROR.');
} else {
console.log('Postgres Connection has been established successfully');
}
});
postgresDB.define('inventory', {
name: Sequelize.STRING,
});
const createSchema = () => {
Business.findAll({
raw: true,
}).then((data) => {
data.forEach((client) => {
postgresDB.createSchema(client.code).then(() => {
Object.keys(postgresDB.models).forEach((currentItem) => {
postgresDB.models[currentItem].schema(client.code).sync();
});
// new schema is created
console.log('Postgres schema created');
}).catch((err) => {
console.log(err.message);
});
});
});
};
createSchema();
// apis
exports.getAllBusiness = (req, res) => {
postgresDB.models.inventory.schema(req.user.code).findAll()
.then((results) => {
res.send(results);
});
};
exports.postBusiness = (req, res) => {
const user = {
name: req.body.name,
};
postgresDB.models.inventory.schema(req.user.code).create(user)
.then(data => res.status(200).send(data))
.catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))
.catch(err => res.status(400).send(err.message));
};
最后,我为每个客户机创建了干净的单独模式,而不是调用
constsequelize=newsequelize(stuff)
在程序开始时,等待填充,然后调用它?我不明白你的问题是什么,tbh。我不明白,有什么基本的例子吗?@ChrisG每个客户端都有多个子域,我想连接多个数据库。登录后,调用new Sequelize(…)
创建第二个连接。我仍然不明白您在哪里被困在这个问题上。所以我想从req.user.session获取dbname和主机内容?我说的对吗?这似乎是个不错的方法,但我很惊讶地看到这种方法有1000多个客户。您将为所有1000个客户端创建1000多个模式。这不是在制造性能问题吗?