Issue
Coming from the world of PHP (Laravel/Eloquent, Symfony/Doctrine) I am used to ORMs not dictating schema but making accessible schema attributes, meaning I've never used a "Model" file to maintain schema, rather schema was maintained by migrations.
In trying to hone my NodeJS/TypeScript skills I am attempting to use TypeORM in the same way, table schemas are to be handled by migrations whereas Model files allow access to table attributes via code. After some reading and trial programming I am realizing that TypeORM doesn't seem to support this type of separation, it seems they force us to use 'Entities' which require Entity metadata which dictate schema.
My question is, is it possible to configure TypeORM so table schema is handled only by migrations, with 0 affect by Model files?
Solution
You can't really avoid entities altogether in TypeORM. But there are a few schools of thought here:
You can have entities that not only define column names and types, but the entire schema (like keys, relationships, indexes, constraints, etc). But this doesn't look like what you want. So alternatively:
You can define entities that are very "plain" and just act like simple objects to access the data. Then:
You can (and probably should, use entity schemas - which are kind of designed for your use case) - you can find more information here: https://orkhan.gitbook.io/typeorm/docs/separating-entity-definition
Or:
- You can use purely migration files where you define the entire schema, including columns, types, key constraints, and so forth. And always update migrations when you want to make changes to the table. But say, you remove a column down the road? You need to manually go to the "entity" file that's acting like a simple class/pojo - and remove whatever column there as well. But entities won't be tied to migrations this way.
Example of your simple POTO: https://www.tutorialspoint.com/typeorm/typeorm_migrations.htm
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Book {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
text: string;
}
Example of the equivalent migrations file:
// XXXXXXXX0001-CreateBookTable.ts
import { MigrationInterface, QueryRunner, Table } from 'typeorm';
export class CreateBookTable implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(new Table({
name: 'book',
columns: [
{ name: 'id', type: 'int', isPrimary: true },
{ name: 'title', type: 'varchar' },
{ name: 'text', type: 'varchar' }
],
}), true);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable('book');
}
}
I hope this helps.
However, why not embrace the most commonly used approach of TypeORM to learn something new, that would probably be best and you'll get more widespread support and help.
Answered By - creativityoverflow
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.