TypeORM generic findByOne, FindOptionsWhere error

问题描述 投票:0回答:1

我有一个使用 TypeORM 的 Nestjs 项目。我创建了

BaseRepositoryInterface
BasRepository
抽象类。 这是
BaseRepositoryInterface

import { DeepPartial, FindManyOptions } from "typeorm";

export interface BaseRepositoryInterface<T> {
    create(data: DeepPartial<T>): T
    findOneById(id: number): Promise<T>
    findAll(options?: FindManyOptions<T>): Promise<T[]>
}

和 BaseRepository 类:

import { DeepPartial, FindManyOptions, FindOptionsWhere, Repository } from "typeorm";
import { BaseRepositoryInterface } from "./base.interface.repository";

export abstract class BaseRepository<T> implements BaseRepositoryInterface<T> {
    private entity: Repository<T>;

    protected constructor(entity: Repository<T>) {
        this.entity = entity;
    }

    public create(data: DeepPartial<T>): T {
        return this.entity.create(data)
    }

    public async findOneById(id: number): Promise<T> {
        const options: FindOptionsWhere<T> = { id: id } // here is the error
        return await this.entity.findOneBy(options)
    }

    public async findAll(options?: FindManyOptions<T>): Promise<T[]> {
        return await this.entity.find(options)
    }
}

但是我在 findOneBy 方法中得到了错误。错误是:

我该如何解决这个错误?我在typeorm github page找到了问题,但是问题还没有解决

javascript node.js nestjs repository typeorm
1个回答
0
投票

首先,您需要使用 IEntity 接口将 id 定义为数字,然后 T 扩展 IEntity

import { DeepPartial, FindManyOptions , FindOneOptions } from "typeorm";

export interface IEntity {
  id: number;
}

export interface BaseRepositoryInterface<T> {
    create(data: DeepPartial<T>): T
    findOneById(id: number): Promise<T | null>
    findAll(options?: FindManyOptions<T>): Promise<T[]>
}

import { FindOptionsWhere, Repository } from "typeorm";

export abstract class BaseRepository<T extends Record<string, any> & IEntity> implements BaseRepositoryInterface<T> {
    private entity: Repository<T>;

    protected constructor(entity: Repository<T>) {
        this.entity = entity;
    }

    public create(data: DeepPartial<T>): T {
        return this.entity.create(data)
    }

    public async findOneById(id: number): Promise<T | null> {
       const options: FindOneOptions<T> = {
      where: {
        id: id,
      } as FindOptionsWhere<T>,
    };
    return await this.entity.findOne(options);
    }

    public async findAll(options?: FindManyOptions<T>): Promise<T[]> {
        return await this.entity.find(options)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.