Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS Create Base CRUD Service

Tags:

nestjs

I am writing my first REST API with nestjs.

I have several entities for which I have to define basic CRUD operations. I was wondering if there is a way to create a base crud service that I can use in order not to repeat the same code for all entities. In this base-crud service I would have the four CRUD methods that call the repository in order to actually do the db related stuff.

Basically I was hoping to have a BaseCrudService<T> and than have a UserService that extends BaseCrudService<UserEntity>. This way I could "override" methods in the derived class to do extra logic business and than call the base method to actually insert, delete etc.

Is it possible? If so, how would you go about to do it?

like image 498
Aaron Ullal Avatar asked Jun 27 '18 06:06

Aaron Ullal


2 Answers

Create a base-crud service as follows :

export class BaseCrudService<Entity extends BaseEntity> {

    constructor(
        public repository: Repository<Entity>,
    ) { }

    async insertAsync(entity: Entity): Promise<InsertResult> {
        return this.repository.insert(entity);
    }
    ...
}

And than have the individual services extend that class :

@Injectable()
export class UserService extends BaseCrudService<UserEntity>{
  constructor(
    @InjectRepository(UserEntity)
    public repository: Repository<UserEntity>,
  ) {
    super(repository);
  }
}

Et-voilà now you have insert, delete, update etc already taken care of..and this for all services that extend the class.

Following this logic you can easily create a BaseCrudController.

like image 53
Aaron Ullal Avatar answered Oct 14 '22 05:10

Aaron Ullal


I've built a package that helps to create CRUD services and controllers without inheritance https://www.npmjs.com/package/@nestjsx/crud

like image 5
Michael Yali Avatar answered Oct 14 '22 04:10

Michael Yali