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?
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
.
I've built a package that helps to create CRUD services and controllers without inheritance https://www.npmjs.com/package/@nestjsx/crud
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With