DEV Community

bc-nguyen
bc-nguyen

Posted on • Edited on

create generic BaseService working with TypeORM

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

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;
}
Enter fullscreen mode Exit fullscreen mode

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();
    }

    //...
}
Enter fullscreen mode Exit fullscreen mode

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;
    }

    //...
}
Enter fullscreen mode Exit fullscreen mode

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)