7

I am learing Nest.js and on the beging of documentation I read that I can use it not only with express but also with fastify so I setuped up my first project with fastify then I started to read about controllers and I found a problem. For example if I want to get more information about user request i can slightly use @Req req: Reguest and this req is type of Request and it is very easy to get this interface from express based application, yuo only have to install @types/express and then you can inport Request interface from express but how(if it is possible) I can get Request interface if I am using fastify?

3 Answers 3

5

So I lay down that types for fasify are already inside Nest projects because they are coming from @types/node. If you want to use interfaces fro fastify just import them from fastify module. Example:

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

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

  @Get('add')
  addTwoNumbers(@Query() query: DefaultQuery): number {
    return this.appService.addTwoNumbers(query.value);
  }
}

If you want to read more about types in fastify visit this link: Fastify Types

1
  • 1
    I'm using nestjs and fastify... I want to type my @Res but I'm not able to find the correct type/import. The import { Reply } from 'fastify'; returns an error message: Cannot find module 'fastify' or its corresponding type declarations.ts(2307)
    – hsantos
    Jan 11, 2023 at 2:17
1

Install the fastify package and import FastifyRequest and FastifyReply from there:

import { Controller, Get, Req, Res } from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';

@Controller('feature')
export class FeatureController {
  @Get()
  async handler(
    @Req() req: FastifyRequest,
    @Res() reply: FastifyReply,
  ) { }
}
0

There should be types from @types/fastify that you can install. I believe Fastify uses Request and Reply as Request and Response.

2
  • No there is no any :/ but actually i found solution. Fastify provides interfaces with @types/node and you can import them from 'fastify' for example DefaultQuery. So if you have installed @types/node(for nest they are already inside the project so you do not have to) you can easy acces them. Here i found my solution fastifyTypes Oct 29, 2019 at 17:52
  • Do you know if express supports that kind of interface?
    – Aladin
    Jun 27, 2020 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.