简体   繁体   中英

How to initialize a TypeORM Repository based on a Generic Type "T" using getRepository()?

db.ts initializes TypeORM :

import { DataSource } from "typeorm"
import { Student, Teacher } from "core"
export class Database {
    public static AppDataSource: DataSource;
    static init () {
        try {
            Database.AppDataSource = new DataSource({
                type: "mysql",
                host: process.env.MYSQL_HOST || config.get('DBHost'),
                port: Number(process.env.MYSQL_PORT || config.get('Port')),
                username: process.env.MYSQL_USER || config.get('Username'),
                password: process.env.MYSQL_PASSWORD || config.get('Password'),
                database: process.env.MYSQL_DB || config.get('Database'),
                entities: [Student, Teacher],
                synchronize: true,
                logging: false,
            })
            // to initialize initial connection with the database, register all entities
            // and "synchronize" database schema, call "initialize()" method of a newly created database
            // once in your application bootstrap
            Database.AppDataSource.initialize()
                .then(() => {
                    // here you can start to work with your database
                    console.log("TypeORM initialized successfully!")
                })
                .catch((error) => console.error(`TypeORM initialization failed! ${error}`))
        } catch (error) {
            console.error('[mysql.connector][init][Error]: ', error);
            throw new Error('failed to initialized pool');
        }
    }
}

In RepositoryBase.ts :

import { IRepository, EntityBase } from "core"
import { Database } from "../../db"
export abstract class RepositoryBase<T extends EntityBase> implements IRepository<T> {
    protected _repository;
    constructor() {
        Database.AppDataSource.getRepository(T); // XXX
    }
}

Error on line marked XXX : 'T' only refers to a type, but is being used as a value here.ts(2693) I have checked out How to initialize a TypeORM Repository based on a Generic Type "T"? but it uses Connection which doesn't apply here.

export abstract class RepositoryBase<T extends EntityBase> implements IRepository<T> {
    protected _repository;
    constructor(entity: EntityTarget<T>) {
        this._repository = Database.AppDataSource.getRepository(entity);
    }
export class UserRepository<Student extends EntityBase> extends RepositoryBase<Student> {
    constructor() {
        super(Student);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM