Tryam
Tryam

Reputation: 405

How to make database request in Nest.js decorator?

I want to find a table row by request parameter. I know how to do it in service but I'm trying to do it also in decorator.

My decorator:

import { BadRequestException, createParamDecorator, ExecutionContext } from '@nestjs/common';

export const GetEvent = createParamDecorator((data: unknown, ctx: ExecutionContext) => {
  const request = ctx.switchToHttp().getRequest();
  const { eventId } = request.params;
  // Something like in service:
  // const event = await this.eventModel.findByPk(eventId);
  // return event;
});

I know that it's impossible to inject service in decorator but maybe some hacks to make database requests before calling service methods?

Upvotes: 10

Views: 5146

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70111

Theoretically, you could use a pacakge directly (like if you use TypeORM you could use the typeorm package), but there's a few things to note:

  1. decorators really shouldn't be calling databases, it'll lead to crazy difficult stack traces
  2. decorator methods can't be async, so you'd need callbacks, which decorators don't really work well with
  3. querying the database really should be done in the controller or service. Just a best practice.

Upvotes: 13

Related Questions