This content originally appeared on DEV Community and was authored by bc-nguyen
In this post I will show you a way to create a base domain service to obtain less code result when working with TypeORM.
Requirements
- Typescript knowledge
- TypeORM knowledge
- Javascript's Mixin
Base Service Design
import { EntityTarget, Repository, DataSource } from 'typeorm';
export const BaseDomainService = <T>(entity: EntityTarget<T>) => {
class DomainServiceMixin {
protected repository: Repository<T>;
constructor(ds: DataSource) {
this.repository = ds.getRepository(entity);
}
};
return DomainServiceMixin;
}
Make sure your tsconfig.json do not turn on declaration
option.
Inherit from Domains
for example you have User & Post domains in your sources, so I can simple to create service for each domains as below explain.
UserSerivce
import { BaseDomainService } from 'basedomainservicepath';
import { User } from 'typeorm user entity paths';
export class UserService extends BaseDomainService(User) {
async getAllUser(): Promise<User[]> {
return await this.repository.find();
}
//...
}
PostService
import { BaseDomainService } from 'basedomainservicepath';
import { Post } from 'typeorm post entity paths';
export class PostService extends BaseDomainService(Post) {
async deletePostById(id: number): Promise<boolean> {
const result = await this.repository.delete(id);
return !!result.affected;
}
//...
}
Conclusion
By implementing Base Service in this way you can prevent repeating implement construct for each domain service.
In next post I will show you how to using with other DI package like awilix , tsyringe, etc...
This content originally appeared on DEV Community and was authored by bc-nguyen
bc-nguyen | Sciencx (2022-07-06T15:47:34+00:00) create generic BaseService working with TypeORM. Retrieved from https://www.scien.cx/2022/07/06/create-generic-baseservice-working-with-typeorm/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.