Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a generic repository with TypeORM

It's my first topic here and my question is why I have a issue when I try to make a generic repository in TypeORM, lets go to the code:

import Car from "../entities/car";
import dataSource from "./../../config/dataSource";
import GenericRepository from "./genericRepository";
export default class CarRepository extends GenericRepository<Car>{
    constructor() {
        super(dataSource.getRepository(Car));
    }

    async findById(object: Car): Promise<Car | null> {
        return await this.repository.findOne({ where: [{ id: object.id }] });
    }

This is a concrete findOne with runs normal, but this is my generic repository

import { Repository } from "typeorm";
import IEntity from "../entities/IEntity";
import { IReposytory } from "./IRepository";

export default abstract class GenericRepository<T extends IEntity> implements IReposytory<T> {

    protected repository: Repository<T>

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

    async save(object: T) {
        await this.repository.save(object);
    }
    async update(object: T) {
        await this.repository.delete(object.id);
        await this.repository.save(object);
    }
    async findAll(): Promise<Array<T>> {
        return await this.repository.find();
    }
    async findById(object: T): Promise<T | null> {
        return await this.repository.findOne({ where: [{ id: object.id }] });
    }
    async find(objectQuery: T): Promise<Array<T>> {
        throw new Error("Method not implemented.");
    }
    async delete(object: T) {
        await this.repository.delete(object.id);
    }

}

In my findById the findOne give me a error :

The type '{ id: number; }[]' cannot be assigned to type 'FindOptionsWhere<T> | FindOptionsWhere<T>[] | undefined'.
  The type '{ id: number; }[]' cannot be assigned to type 'FindOptionsWhere<T>[]'.
    The type '{ id: number; }' cannot be assigned to type 'FindOptionsWhere<T>'.

I have find nothing about this in the documentation, someone a help :/?

I have continuited typing in the comcrete class to continue my project

like image 752
Marcelo Hernades Romano Avatar asked Oct 29 '25 14:10

Marcelo Hernades Romano


1 Answers

public async findOne(id: number): Promise<T> {
    return await this.repository.findOneBy({ id } as FindOptionsWhere<T>)
}
like image 57
Felipe Gabriel dos Santos Avatar answered Oct 31 '25 04:10

Felipe Gabriel dos Santos