NestJS + TypORM design patterns: resolver vs service

1.6k Views Asked by At

I've found numerous examples of nest 'example' apps, but each one seems to have slightly different opinions on design patterns. I'm currently interested in where the object preparation work should go between a resolver and service when coupled with TypeORM.

for example:

comment.resolver.ts:

/********************
 * @MUTATION
 *********************/

/**
 *
 * @param payload
 * @param args
 */
@Mutation('createComment')
async create(@CurrentUser() payload: JwtPayload, @Args('input') args: CreateCommentInputDto): Promise < CommentEntity > {
  const currentUser = await this.userService.getCurrentUser(payload);
  const initComment = new CommentEntity();
  const newComment: CommentEntity = {
    ...args,
    createdBy: currentUser,
    createdDate: new Date(),
    modifiedDate: new Date(),
    ...initComment,
  };
  const createdComment = await this.commentService.create(newComment);
  pubSub.publish('CommentCreated', {
    CommentCreated: createdComment
  });
  return createdComment;
}

comment.service.ts:

/**
 *
 * @param comment
 */
async create(comment: CommentEntity): Promise < CommentEntity > {
  return await this.CommentsRepository.save(comment);
}

i.e.

  • Create new empty comment Entity
  • Add field values that are not supplied by query
  • use spread operator to combine them all together
  • pass them all to the comment service to save via TypeORM repository

The reasoning being that the comment service just accepts and saves a well formatted entity. Maybe in the future I i will need to prepare the comment to be created in a different way, and so that would be defined in a new mutation.

Is this an anti-pattern? Should I be moving that object create / combine / formatting into the service, and keep the resolver method as light as possible?

If so, what's the logic behind that?

1

There are 1 best solutions below

0
On

You should check the preload method that is provided by the Repository item provided by TypeOrm. It allows batching changes on an existing entity or new one, which should be what you want.

I think that TypeOrm is very unopiniated, you are free to choose how you organise your mutations on entities. Still I think the 'preload' repository pattern is a safe one as you always want first to get value from the database corresponding to your proposed changes, then you batch the changes in the entity and save it afterwards. It should lower your chances of getting a conflict value on an entity or getting double values etc.

You can see the database as a git repository, fetch first, rebase your local changes on the remote head value, commit and push your changes.