doug-martin / nestjs-query

Easy CRUD for GraphQL.
https://doug-martin.github.io/nestjs-query
MIT License
822 stars 142 forks source link

Question: Where is it supposed to put my business logic? #868

Closed ezdookie closed 3 years ago

ezdookie commented 3 years ago

I've been learning nestjs and nestjs-query since few days ago. This solution brings a fully working CRUD and documentation doesn't let me clearly understand where to put my business logic after creating/updating my object, for example, adding jobs to queues. I understand there are hooks but it works only at before creating the object, but not after.

Also I see the posibility of overwriting the CreateResolver (https://doug-martin.github.io/nestjs-query/docs/graphql/resolvers/#createresolver) but I would like to know if this is the right way. Thanks in advance.

doug-martin commented 3 years ago

@ezdookie I'm not sure which persistence adapter you are using but for each query service each you can implement your own version by extending the persistence query service class.

See:

For example you could override the create method by doing the following

import { QueryService } from '@nestjs-query/core'
import { TypeOrmQueryService } from '@nestjs-query/query-typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TodoItemEntity } from './todo-item.entity';

@QueryService(TodoItemEntity)
export class TodoItemService extends TypeOrmQueryService<TodoItemEntity> {
  constructor(
    @InjectRepository(TodoItemEntity) repo: Repository<TodoItemEntity>,
  ) {
    super(repo);
  }

  async createOne(todoItem: Partial<TodoItemEntity>): Promise< TodoItemEntity > {
      // do some before logic
      const created = await super.createOne(todoItem);
      // do some after logic
     return created; 
  }
}

You could do the same pattern for createMany, updateOne, or updateMany

Hope this helps!