Skip to content

Instantly share code, notes, and snippets.

@umarov
Last active February 23, 2019 16:55
Show Gist options
  • Save umarov/fd4c939f7112ffc44a8b82e2930888e7 to your computer and use it in GitHub Desktop.
Save umarov/fd4c939f7112ffc44a8b82e2930888e7 to your computer and use it in GitHub Desktop.
Create db and migrations for Node and TypeORM
const util = require("util");
const { Pool } = require("pg");
const { username: user, host, password, port, database } = require("./ormconfig");
const exec = util.promisify(require("child_process").exec);
const baseDatabaseName = process.env.PG_DB;
// This requires an existing DB to exist. That's why `postgres` is being used as the DB
const pool = new Pool({
user,
host,
database: "postgres",
password,
port,
});
async function runMigrations() {
try {
await createEnvDatabase().finally(() => {
return createTestDatabase();
});
} catch (_) {
console.info("Database already exists, continuing with migrations");
// Database already exists
} finally {
await exec("npm run migrations");
console.info("Finished with migrations");
}
}
function createEnvDatabase() {
return pool.query(`CREATE DATABASE "${database}"`);
}
function createTestDatabase() {
return pool.query(`CREATE DATABASE "${baseDatabaseName}-test"`);
}
runMigrations().catch(err => {
console.log(err);
process.exit(0);
});
const dotenv = require("dotenv");
dotenv.config();
const { NODE_ENV } = process.env;
const isDevelopment = NODE_ENV === "development";
const isTest = NODE_ENV === "test";
const isProduction = NODE_ENV === "production";
const isStaging = NODE_ENV === "staging";
const isDevelopmentOrTest = isDevelopment || isTest;
module.exports = {
isDevelopment,
isTest,
isProduction,
isStaging,
isDevelopmentOrTest,
};
// @ts-check
const {
isDevelopment,
isTest,
isProduction,
isStaging,
isDevelopmentOrTest,
} = require("./env");
const {
PG_DB_HOST,
PG_DB_PORT,
PG_DB_USER,
PG_DB_PASSWORD,
PG_DB,
NODE_ENV,
} = process.env;
const entities = isDevelopmentOrTest
? [`./src/**/**/*.entity.ts`]
: [`./dist/src/**/*.entity.js`];
const migrations = isDevelopmentOrTest
? [`./migrations/*.ts`]
: [`./dist/migrations/*.js`];
function logging() {
if (isStaging || isProduction) {
return ["info"];
}
if (isDevelopment) {
return true;
}
if (isTest) {
return ["error"];
}
}
// Base config assumes functionality without docker
// @type { TypeOrmModuleOptions }
const baseConfig = {
type: "postgres",
host: "localhost",
port: 5432,
database: `${PG_DB}-${NODE_ENV}`,
username: PG_DB_USER,
password: PG_DB_PASSWORD,
entities,
migrations,
synchronize: isTest,
logging: logging(),
migrationsTableName: "migrations",
cli: {
migrationsDir: `./migrations`,
},
maxQueryExecutionTime: 1000,
};
// If this is running inside docker
if (PG_DB_HOST) {
module.exports = {
...baseConfig,
host: PG_DB_HOST,
port: PG_DB_PORT,
};
} else {
module.exports = baseConfig;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment