lucasrochagit / nest-mongo-query-parser

A MongoDB query string parser to be used in applications developed with NestJS.
Apache License 2.0
12 stars 8 forks source link

Is it possible to use the param-decorator in service layer? #12

Closed ykh closed 1 year ago

ykh commented 1 year ago

Hi again, If I wanted to use @MongoQuery() in my service layer, is that possible?

lucasrochagit commented 1 year ago

Hello again @ykh.

Yes, it is possible, although it is not as practical as using the controller. The configuration, although not so clear, consists of accessing the query in the controller method through the decorator @Query() from the @nestjs/common library and, in the service, using the decorator @MongoQueryParser() as the decorator of the method that will receive the controller query. Example:

// AppController.ts

import { Controller, Get, Query } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(@Query() query: any) {
    return this.appService.getHello(query);
  }
}

// AppService

import { Injectable } from '@nestjs/common';
import { MongoQueryModel, MongoQueryParser } from 'nest-mongo-query-parser';

@Injectable()
export class AppService {

  @MongoQueryParser()
  getHello(query: MongoQueryModel) {
    return query;
  }
}

And the query treatment will be the same. ;)