2

I am creating a get api in nodejs.I am requesting the following url

http://localhost:8080/api?id=20&condition1=true&arr=[{prop1:1}]&obj={a:1,b:2} And I am getting the request query object as follows-

req.query = {
   arr:"[{prop1:1}]",
   condition1:"true",
   id:"20",
  obj:"{a:1,b:2}" 
}

I want to convert the query object keys to appropriate types.My query object should be converted to

req.query = {
       arr:[{prop1:1}], // Array
       condition1:true, // Boolean
       id:20, // Number
      obj: {a:1,b:2} //Object
    }

req.query object is dynamic, it can contain any number of objects, array, boolean , number or strings. Is there any way to do it?

Komal Bansal
  • 789
  • 2
  • 7
  • 20

1 Answers1

1

This functionality doesn't come out of the box with express and query parameters.

The problem is that in order for the query string parser to know if "true" is actual boolean true or the string "true" it needs some sort of Schema for the query object to help parsing the string.

Option A

What I can recommend is using Joi.

In your case it will look like :

const Joi = require( "joi" );


const querySchema = {
    arr: Joi.array(),
    condition1: Joi.boolean(),
    id: Joi.number(),
    obj: {
      a: Joi.number(),
      b: Joi.number()
    }
}

Having this schema you can attach it to your express method and use Joi.validate To validate it.

function getFoo( req, res, next ) {
    const query = req.query; // query is { condition1: "true" // string, ... }
    Joi.validate( query, querySchema, ( err, values ) => {
        values.condition1 === true // converted to boolean
    } );
}

Option B

Another way of having properly typed GET requests would be to trick the query parameters and just provide a stringified JSON.

GET localhost/foo?data='{"foo":true,"bar":1}'

This will give you the possibility to just parse the request query

function getFoo( req, res, next ) {
    const data = JSON.parse( req.query.data )
    data.foo // boolean
    data.bar // number
}
drinchev
  • 19,201
  • 4
  • 67
  • 93
  • the query string will be dynamic i.e. i don't know which query param will be array or object or boolean. Could you suggest some package for this problem. And I can't use option B because JSON.parse will give error in case of string – Komal Bansal Dec 12 '18 at 05:38
  • 1
    You can use `try { const data = JSON.parse( req.query.data ) } catch ( error ) { // Not JSON }`. This will catch the error of JSON.parse – drinchev Dec 12 '18 at 07:01
  • Option B could be better. – Jerry Jan 29 '23 at 17:33