2020-08-16 23:28:41 -07:00
|
|
|
const mysql = require("mysql2");
|
2020-04-22 11:51:36 -07:00
|
|
|
|
2020-09-19 04:39:08 -07:00
|
|
|
let globalDbs = new Map();
|
2020-04-22 15:53:59 -07:00
|
|
|
|
2020-10-06 06:11:22 -07:00
|
|
|
// We usually run against the production database, even in local testing,
|
|
|
|
// to easily test against real data. (Not a wise general practice, but fine
|
|
|
|
// for this low-stakes project and small dev team with mostly read-only
|
|
|
|
// operations!)
|
|
|
|
//
|
|
|
|
// But you can also specify `DB_ENV=development` to use a local database,
|
|
|
|
// which is especially helpful for end-to-end modeling testing.
|
|
|
|
const defaultOptions =
|
|
|
|
process.env["DB_ENV"] === "development"
|
|
|
|
? {
|
|
|
|
host: "localhost",
|
|
|
|
user: "impress_2020_dev",
|
|
|
|
password: "impress_2020_dev",
|
|
|
|
database: "impress_2020_dev",
|
|
|
|
}
|
|
|
|
: {
|
|
|
|
host: "impress.openneo.net",
|
|
|
|
user: process.env["IMPRESS_MYSQL_USER"],
|
|
|
|
password: process.env["IMPRESS_MYSQL_PASSWORD"],
|
|
|
|
database: "openneo_impress",
|
|
|
|
};
|
|
|
|
|
2020-09-02 03:49:58 -07:00
|
|
|
async function connectToDb({
|
2020-10-06 06:11:22 -07:00
|
|
|
host = defaultOptions.host,
|
|
|
|
user = defaultOptions.user,
|
|
|
|
password = defaultOptions.password,
|
|
|
|
database = defaultOptions.database,
|
2020-09-02 03:49:58 -07:00
|
|
|
} = {}) {
|
2020-09-19 04:39:08 -07:00
|
|
|
if (globalDbs.has(host)) {
|
|
|
|
return globalDbs.get(host);
|
2020-04-22 15:53:59 -07:00
|
|
|
}
|
|
|
|
|
2020-09-19 04:39:08 -07:00
|
|
|
const db = mysql
|
2020-08-16 23:28:41 -07:00
|
|
|
.createConnection({
|
2020-09-18 05:50:17 -07:00
|
|
|
host,
|
2020-09-02 03:49:58 -07:00
|
|
|
user,
|
|
|
|
password,
|
2020-09-18 05:50:17 -07:00
|
|
|
database,
|
2020-09-06 15:49:08 -07:00
|
|
|
multipleStatements: true,
|
2020-08-16 23:28:41 -07:00
|
|
|
})
|
|
|
|
// We upgrade to promises here, instead of using the mysql2/promise import,
|
|
|
|
// for compatibility with Honeycomb's automatic tracing.
|
|
|
|
.promise();
|
2020-04-22 11:51:36 -07:00
|
|
|
|
2020-09-19 04:39:08 -07:00
|
|
|
globalDbs.set(host, db);
|
|
|
|
|
|
|
|
return db;
|
2020-04-22 11:51:36 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = connectToDb;
|