TypeORM Custom Decorators

Viewed 1923

I want to be able to add custom decorators to my entity models to mark particular fields for user metadata migration.

For example:

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
import { CreatedBy } from "../subscribers/test";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id!: number;

    @Column()
    name!: string;

    @Migrate()
    userValue!: string;
 
    @Migrate()
    specficValue!: string;

}

Where migrate could be like a Column decorator, but I could take a User model, and find all of the properties that have the migrate decorator so that I know which ones to pull forward.

Is there a way to accomplish this in TypeORM?

Thank you for any and all help.

1 Answers

Checkout the following github tapeorm issue: https://github.com/typeorm/typeorm/issues/2711

In specific I would checkout how the 'ColumnCommonOptions' decorator works: https://github.com/typeorm/typeorm/blob/master/src/decorator/options/ColumnCommonOptions.ts

It seems to be quite straight forward:

// MigrateDecorator.ts

import { getMetadataArgsStorage } from "typeorm";
//Optional
import { MigrateOptionsInterface } from './MigrateOptionsInterface'

 export function MigrateDecorator(options?: MigrateOptionsInterface): Function { 
     return function (object: Object, propertyName: string) { 
         getMetadataArgsStorage().columns.push({
           propertyName,
           migrate: options.migrate || false // just an example
         }); 
     }; 
 } 
Related