So I am using typeorm with ormconfig.json.
Since synchronize
cannot be used in production, how can I run the migrations based on entities?
my ormconfig.json
file
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "",
"password": "",
"database": "backend-api",
"synchronize": false,
"logging": true,
"migrationsRun": true,
"entities": ["dist/entity/**/*.js"],
"migrations": ["dist/migration/**/*.js"],
"subscribers": ["dist/subscriber/**/*.js"],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
Also here is my only Todo.ts
entity file
import {
BaseEntity,
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
@Entity()
export class Todo extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('text')
text: string;
@Column('boolean', { default: false })
completed: boolean;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
Got the solution for this problem.
So my ormconfig.json
needed a slight update,
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "",
"password": "",
"database": "backend-api",
"synchronize": false,
"logging": true,
"migrationsRun": false,
"entities": ["src/entity/**/*.ts"],
"migrations": ["src/migration/**/*.ts"],
"subscribers": ["src/subscriber/**/*.ts"],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
and i needed to install ts-node
to compile the ts
entity and migration files.
I created the below mentioned scripts:
"scripts": {
"start": "ts-node src/index.ts",
"entity:create": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm entity:create -n",
"migrate:generate": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:generate -n",
"migrate:run": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:run",
"migrate:revert": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:revert",
"schema:drop": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm schema:drop"
}
and in the order of the script.
The one thing I learned is you cannot simply crate an entity file and run migration:generate
on it. You first need to create an entity based on typeorm
cli. I don't know why, but for me once I started creating the entity using the cli everything fallen into place
To run the migrations based on entities, you can generate the migrations files from your entities as said in the TypeOrm documentation about generating migrations.
TypeORM is able to automatically generate migration files with schema changes you made.
Run this command specifying the name of the migration to generate the file:
typeorm migration:generate -n <MigrationName>
After it, you just need to run your migrations by using the CLI:
typeorm migration:run
A good practice is to use the migrationsRun
parameter to your database configuration to run your migrations on start:
migrationsRun: true,