本文介绍了Typeorm 自定义装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够向我的实体模型添加自定义装饰器,以标记特定字段以进行用户元数据迁移.

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

例如

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;

}

其中 migrate 可能类似于 Column 装饰器,但我可以采用 User 模型,并找到具有 migrate 装饰器的所有属性,以便我知道要推进哪些属性.

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.

有没有办法在 TypeORM 中实现这一点?

Is there a way to accomplish this in TypeORM?

感谢您的任何帮助.

推荐答案

检查以下 github Tapeorm 问题:https://github.com/typeorm/typeorm/issues/2711

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

具体来说,我会检查ColumnCommonOptions"装饰器的工作原理:https://github.com/typeorm/typeorm/blob/master/src/decorator/options/ColumnCommonOptions.ts

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

这似乎很简单:

// 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
         }); 
     }; 
 } 

这篇关于Typeorm 自定义装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 10:58