Search code examples
node.jstypescriptexpress

How to parse request body of POST method in typescript?


We have a backend API which expects below type in the request body.

type taskslistrequest = {
    clientgroupcode: string[];
    startindex: number;
    pagesize: number;
}

This is how I am parsing the request body:

const tasklistreq: taskslistrequest = req.body.taskslistrequest as taskslistrequest;

However, typescript doesn't throw any error if I send below request body from postman.

{
    "taskslistrequest": {
        "clientgroupcode": [
            "AAB",
            "AAC",
            "AAD"
        ],
        "startindex": "0",
        "pagesize": "50"
    }
}

Can you please help me to understand how can I make sure that if there is any type mismatch then it is captured while parsing the request body itself.

I am using:

  1. Typescript - 5.3.3
  2. NodeJS - 20.10.0
  3. Express - 4.18.2

Solution

  • I like to validate my request with joi it would probably look like this:

    const fooValidation = Joi.object({
      var1: joi.array().required().items(
        Joi.string())
      var2: Joi.number().required()
      var3: Joi.string()
     })
     
     fooValidation.validate(req.body)
    

    look at the documentation https://joi.dev/