TypeORM generic findByOne, FindOptionsWhere error

编程入门 行业动态 更新时间:2024-10-06 04:06:04

TypeORM <a href=https://www.elefans.com/category/jswz/34/1703654.html style=generic findByOne, FindOptionsWhere error"/>

TypeORM generic findByOne, FindOptionsWhere error

我有一个使用 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找到了问题,但是问题还没有解决

回答如下:

首先,您需要使用 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)
    }
}

更多推荐

TypeORM generic findByOne, FindOptionsWhere error

本文发布于:2024-05-30 15:43:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770655.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:generic   TypeORM   findByOne   error   FindOptionsWhere

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!