【问题标题】:typeorm convert EntitySchema to Entitytypeorm 将 EntitySchema 转换为 Entity
【发布时间】:2020-12-07 19:11:58
【问题描述】:

我正在使用 typescript 和 typeorm。我有这个实体:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Sample {

    @PrimaryGeneratedColumn()
    id: number;

    @Column({ length: 50 })
    name: string;

    @Column('text', { nullable: true })
    description: string;
}

我这样查询一个结果:

const connection = await this.getConnection();
const sampleRepo = await connection.getRepository(Sample);
const sample = await sampleRepo.createQueryBuilder('sample')
    .where('sample.id = :id', { id: id })
    .getOne();

现在,我需要对结果列进行一些处理,但示例对象的类型为 EntitySchema。所以,在打字稿中,我不能做sample.id,因为错误:

Property 'id' does not exist on type 'EntitySchema<any>'

是否可以将EntitySchema 转换为实际的Sample 对象?

【问题讨论】:

  • 我猜您的 sampleRepo 创建不正确。它应该类似于getRepository(Sample)
  • 我添加了我创建存储库的方式
  • 嗯,应该可以。这是文档中的内容
  • 您可能想从尝试开始: const sample = await getRepository(Sample).createQueryBuilder('sample') .where('sample.id = :id', { id: id }) 。 getOne();` 链接这些承诺可能会产生不利影响并破坏某处的引用。

标签: node.js typescript typeorm


【解决方案1】:

事实证明,这是由于实施不当造成的。我将存储库的创建移到了一个单独的类中:

export default class Database {
    private connectionManager: ConnectionManager

    constructor() {
        this.connectionManager = getConnectionManager();
    }

    public getRepository<T extends EntitySchema>(type:  ObjectType<T> | EntitySchema<T> | string): Promise<Repository<T>> {
        const connection = await this.getConnection();
        return connection.getRepository(type);
    }

    public async getConnection(connectionName = 'default'): Promise<Connection> {
        let connection: Connection;

        if (this.connectionManager.has(connectionName)) {
            connection = this.connectionManager.get(connectionName);

            if (!connection.isConnected) {
                connection = await connection.connect();
            }
        }
        else {
            const connectionOptions: ConnectionOptions = Object
                .assign({ name: connection }, connectionProperties);

            connection = await createConnection(connectionOptions);
        }

        return connection;
    }
}

看起来connection.getRepository 没有返回承诺。同样,T 泛型不应该扩展EntitySchema。为了使函数按预期工作,我必须这样写:

public getRepository<T>(type:  ObjectType<T> | EntitySchema<T> | string): Promise<Repository<T>> {
    return new Promise((resolve, reject) => {
        this.getConnection().then(conn => {
            resolve(conn.getRepository(type));
        }).catch(reject);
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-23
    • 2021-10-08
    • 2022-08-19
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    相关资源
    最近更新 更多