5

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?

Krzysztof Kaczyński
  • 4,412
  • 6
  • 28
  • 51

3 Answers3

4

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

Krzysztof Kaczyński
  • 4,412
  • 6
  • 28
  • 51
  • 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 '23 at 02:17
0

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

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • 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](https://www.fastify.io/docs/latest/TypeScript/#core-types) – Krzysztof Kaczyński Oct 29 '19 at 17:52
  • Do you know if express supports that kind of interface? – Aladin Jun 27 '20 at 09:56
0

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,
  ) { }
}
Maksym B.
  • 61
  • 5