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...
Top comments (0)