Home > Software engineering >  Nestjs create Generic CRUD service
Nestjs create Generic CRUD service

Time:05-01

I want to create a base service using a generic class which I wrote below:


import { BaseEntity } from './base.entity';
import { Repository } from 'typeorm';

export class BaseService<Entity extends BaseEntity> {
  constructor(private entitiesRepository: Repository<Entity>) {}

  findById(id: number): Promise<Entity> {
    return this.entitiesRepository.findOneBy({ id });
  }
}

When I try it, I get the following error:

Argument of type '{ id: number; }' is not assignable to parameter of type 'FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]'.
Types of property 'id' are incompatible.     
Type 'number' is not assignable to type 'FindOptionsWhereProperty<NonNullable<Entity["id"]>>'


This is my base entity class:

// base.entity.ts
import {
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
} from 'typeorm';

export class BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ default: false })
  isDeleted: boolean;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

How can I fix this problem?

CodePudding user response:

I think you are using an outdated version of typeorm. findOneBy is deprecated and removed in the recent releases.

Update typeorm and try this:

findById(id: number): Promise<Entity> {
    return this.entitiesRepository.findOne(id);
}

CodePudding user response:

You need to decorate your BaseEntity class @Entity() as stated in the documentation : https://docs.nestjs.com/techniques/database#repository-pattern

// base.entity.ts
import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
} from 'typeorm';

@Entity()
export class BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ default: false })
  isDeleted: boolean;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}
  • Related