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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With