Of the several ways of connecting to a database offered by TypeORM (json, env, yml...) I choose to set my Connection Options programatically within my project's code using a regular TypeScript file as follows:
// src/database/createConnection.ts
import { createConnection } from 'typeorm';
const connectionOptions = {
type: 'postgres',
host: POSTGRES_HOST_PROD,
port: Number(POSTGRES_PORT),
username: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: POSTGRES_DB,
entities: ['build/entities/**/typeDef.js'],
migrations: ['build/database/migrations/*.js'],
cli: {
migrationsDir: 'src/database/migrations/'
}
};
await createConnection(connectionOptions);
With the values fed by a regular .env
file.
My problem is that when trying to create migration files through npx typeorm migration:generate -n initial
I get an error as the command expects a specific orm configuration file to be present (ormconfig.env, ormconfig.json, etc).
As I already have my connection options set, this is not only redundant, it would also be processed instead of the configuration I have already set in the .ts
file, and the only solution I see would be to rename the variables in my (non-typeorm-specific) .env
file to match the specific TypeORM variable names, which I'd prefer not to do.
TL:DR Is there a way of generating TypeORM migrations without creating a dedicated orm config file?
Oh, turns out TypeORM already has a built-in option for this which does not require an extra ormconfig file, one can just add the property migrationsRun: true
to the Connection Options (making sure synchronize
is set to false).
For instance:
import { createConnection } from 'typeorm';
const connectionOptions = {
type: 'postgres',
host: POSTGRES_HOST_PROD,
port: Number(POSTGRES_PORT),
username: POSTGRES_USER,
password: POSTGRES_PASSWORD,
database: POSTGRES_DB,
migrationsRun: true,
entities: ['build/entities/**/typeDef.js'],
migrations: ['build/database/migrations/*.js'],
cli: {
migrationsDir: 'src/database/migrations/'
}
};
await createConnection(connectionOptions);