Fastify Typescript: dealing with an unidentified body

I'm new to Fastify and I've encountered a problem with accessing values in the body using Typescript. Does anyone have any ideas or suggestions? Thanks!

Update: I want to simplify my code and avoid using app.get(...)

Here's my code snippet:

App.ts

const buildServer = (options = {}) => {
  const app = fastify(options);
  app.register(routesApiV1, { prefix: '/api'});
  return app;
}

Routes.ts

const routesApiV1: FastifyPluginCallback = (fastify, options, done) => {
  fastify.route(userRoute);
  done();
}

User.ts

const handler: RouteHandlerMethod = async (req, res) => {
  const {
    name,
    lastName,
    dateOfBirth,
    addressLine,
    zipCode,
    city,
    country
  } = req.body; // Property '...' does not exist on type 'unknown'
  
  ...
}

const route: RouteOptions = {
  method: 'GET',
  url: '/user/:id',
  // schema: fastifySchema, Tried but not working
  handler,
  preValidation,
}

Answer №1

The generic type FastifyRequest requires passing your body type as a parameter...

import type { FastifyRequest } from 'fastify'

interface BodyType {
  name: string
}

const handler = async (req: FastifyRequest<{ Body: BodyType }>) => {
    const { name } = req.body
}

When using RouteHandlerMethod, the request object is typed as

FastifyRequest<{ Body: unknown }>
by default, resulting in the body type being unknown.

Answer №2

To ensure proper functionality, it is necessary to define the types for RouteHandlerMethod and RouteOptions as follows:

The types

type Body = {
  name: string;
  // ...
}

type Response = {
   // ...
}

RouteHandlerMethod

import { RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault, RouteHandler, RouteHandlerMethod } from "fastify";

const handler: RouteHandlerMethod<
    RawServerDefault,
    RawRequestDefaultExpression,
    RawReplyDefaultExpression,
    { Reply: Response; Body: Body }
>  = async (req, res) => {
  const {
    name,
    lastName,
    dateOfBirth,
    addressLine,
    zipCode,
    city,
    country
  } = req.body; // Property '...' does not exist on type 'unknown'
  
  ...
}

RouteOptions

import { RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault, RouteHandler, RouteHandlerMethod, RouteOptions } from "fastify";

const route: RouteOptions<RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
{ Reply: Response, Body: Body }> = {
  method: 'GET',
  url: '/user/:id',
  // schema: fastifySchema, Tried but not working
  handler,
  preValidation,
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

What is the reason behind the return type of 'MyType | undefined' for Array<MyType>.find(...) method?

Currently, I am in the process of developing an Angular application using TypeScript. As part of this project, I have defined several classes along with corresponding interfaces that align perfectly with their respective properties: Map: export class Map ...

Display a symbol retrieved from the backend server

After receiving a response from the backend server for my Angular 2/4 application, I am presented with an attribute called "connectionStatus". This attribute indicates the status of a database connection, either as "UP" or "DOWN". In order to display this ...

Having trouble getting Jest to manually mock in Nestjs?

When setting up a mock service like this: // /catalogue/__mock__/catalogue.service.ts export const CatalogueService = jest.fn().mockImplementation(() => { return { filterRulesFor: jest.fn().mockImplementation((role: Roles): Rule[] => rules.filt ...

Troubleshooting issues with importing modules in TypeScript when implementing Redux reducers

Struggling to incorporate Redux with TypeScript and persist state data in local storage. My current code isn't saving the state properly, and as I am still new to TypeScript, I could really use some suggestions from experienced developers. Reducers i ...

Customizing the file path for the PDF worker: A step-by-step guide

Incorporating the PDF Viewer Component from this source into an Angular 7 project has been a challenge. The documentation clearly states: The default worker is loaded from cdnjs.cloudflare.com. My goal is to load the worker from a local path within my ...

What is the process for eliminating the perplexing "default" attribute that has been inserted into JSON?

I recently came across the jsondata.json file: { "name": "John", "age": 30, "car": "ferrari" } Located in the same directory is a typescript file called main.ts where I simply output the json data using console.log import * as j from '. ...

Cannot instantiate Marker Clusterer as a constructor

I am facing an issue with implementing Marker Clusterer in my app. I have successfully installed '@google/markerclusterer' in my project and imported it as shown below. However, a puzzling error keeps popping up: core.js:4002 ERROR TypeError: _go ...

Dynamic rows in an Angular 2 Material data table

I'm currently working on dynamically adding rows to an Angular 2 Data Table ( https://material.angular.io/components/table/overview) by utilizing a service called "ListService". This service provides me with the columns ("meta.attributes") to be displ ...

Retrieve information using Angular's EventEmitter

Recently I started learning Angular and encountered a challenging issue that has kept me occupied for the past few hours. I have implemented a parent-child relationship between two components, with a need to share a boolean variable from the parent to the ...

The combination of arrays and array methods in intersection types may encounter difficulty in accessing all fields

I have two different types, both in the form of arrays of objects with specified fields, combined into an intersection type in Typescript. When I access an element from the array, I can retrieve the second field without any issues. However, when I try to ...

Draggable bar charts in Highcharts allow users to interact with the data by clicking

I'm working on creating a chart that allows for setting values by clicking and dragging. While the dragging functionality is working fine, I've run into an issue with the click event. When I click to set a new value, the draggable feature acts er ...

JavaScript: Translating Date into Moment

Is there a way to convert a Date object to Moment in JavaScript? let testDate = new Date(2020, 05, 03, 1, 2); I attempted the following code without success toMoment(testDate) What is the correct syntax to achieve this conversion? ...

The usage of Angular Tap is no longer recommended or supported

My Angular application contains the following HTTP interceptor: import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpResponse } from '@angular/common/http'; ...

If you're setting up a new Next.js and Tailwind CSS application, you can use the flags -e or --example to start the project as a

After several attempts at creating a Next.js app with Tailwind CSS using JavaScript, I keep getting TypeScript files. How can I prevent this error? Despite following the usual commands for setting up a Next.js project, I am consistently ending up with Typ ...

The Axios function is unable to read the 'Ok' value because of undefined properties

I suspect there is something missing in my argument, but I am attempting to call HttpStatusCode.Ok from the Axios Enum. Here is how I have implemented it: import { HttpStatusCode } from 'axios' console.log(HttpStatusCode.Ok) However, I encounte ...

Encountering an issue when utilizing inversifyJS inject with the error message "Reading '_userService' cannot be done as it is undefined."

I'm currently working on implementing a DI system, but it seems like I may be missing some key concepts of Inversify. Do I need to create a "get" method for the "user.controller" and then "bind" it to the routes function? Link to complete code reposi ...

This element is not suitable for use as a JSX component since its return type 'void' is not a valid JSX element. Please check the return type to ensure it is compatible with

I have been working on this code snippet: function searchData(searchWord: any) { if (originalData.length > 0) { if (searchWord !== "") { setDataList([...originalData.filter((svc: any) => ...

Error encountered when transitioning to TypeScript: Unable to resolve '@/styles/globals.css'

While experimenting with the boilerplate template, I encountered an unusual issue when attempting to use TypeScript with the default NextJS configuration. The problem arose when changing the file extension from .js to .tsx / .tsx. Various versions of NextJ ...

JavaScript Class Emit Signal for establishing a sequence of interconnected events

My Vue project includes a JavaScript class specifically for mobile devices. I'm looking to have this class emit a signal once the property 'hasEnded' is set to True for my object. How can I achieve this and chain together other events based ...