node.js - Använda olika ormconfig.json-filer beroende på miljö
Min ormconfig.json är förstås statisk, den ser ut så här:
{
"type": "mariadb",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "moove",
"database": "moove_db",
"synchronize": true,
"logging": false,
"entities": [
"dist/entity/**/*.js"
],
"migrations": [
"dist/migration/**/*.js"
],
"subscribers": [
"dist/subscriber/**/*.js"
],
"cli": {
"entitiesDir": "dist/entity",
"migrationsDir": "dist/migration",
"subscribersDir": "dist/subscriber"
}
}
men vad händer om jag vill skapa en annan konfiguration för vår produktionsserver? Ska jag skapa en annan konfigurationsfil? Hur pekar jag TypeORM till den andra konfigurationsfilen?
Svar #1
För tillfället kunde jag bara ändra ormconfig.json till ormconfig.js och sedan använda miljövariabler, på detta sätt:
module.exports = {
"port": process.env.port,
"entities": [
// ...
],
"migrations": [
// ...
],
"subscribers": [
// ...
],
"cli": {
// ...
}
}
Svar #2
Använd inte ormconfig.json. Du kan skicka ett konfigurationsobjekt direkt till createConnection() som
import { createConnection } from "typeorm";
const config:any = {
"port": process.env.port || "28017",
"entities": [
// ...
],
"migrations": [
// ...
],
"subscribers": [
// ...
],
"cli": {
// ...
}
}
createConnection(config).then(async connection => {
await loadPosts(connection);
}).catch(error => console.log(error));
