typeorm将EntitySchema转换为Entity

问题描述

我正在使用打字稿和打字稿。我有这个实体:

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对象吗?

解决方法

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...