1

Let's say we make the following GET API call to our REST API running with NestJS (and fastify):

http://localhost:5000/api/test?arrayParam=["abc","def"]&anotherParam="value"

Without parsing anything, the query object on the backend looks like this:

{
  arrayParam: '["abc","def"]',
  anotherParam: '"value"'
}

We can see that parameter values are strings, but in the case of arrayParam we would obviously like to work with the actual array.

I come from an expressJS background, and coming from there, there are a couple of approaches. First would be just using a JSON parser middleware, like body-parser. Or just using JSON.parse().

But what is the "proper", NestJS approach? I thought about using type decorators defined in a DTO, and assumed they would be automatically parsed to the type that I defined. But that doesn't work like I assumed it would.

I defined it like this:

  @IsOptional()
  @IsArray()
  arrayParam?: string[];

But validation fails, since arrayParam is a string and not an array. So I assume this is not the correct approach

mythic
  • 895
  • 2
  • 13
  • 31

1 Answers1

0

You are sending it incorrectly

http://localhost:5000/api/test?arrayParam[]=abc&arrayParam[]=def&anotherParam
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • Incorrectly according to nestJS standards? Or REST standards? I might have just learned bad habits, but I want to know, why is it wrong in this case? – mythic Oct 23 '22 at 12:20
  • 1
    I didn't ever see a query string like yours. I've seen only two types supported by express that nest uses internally which is `arrayParam[]=abc&arrayParam[]=def` and `arrayParam=abc&arrayParam=def`. Maybe your style is fine too, but as you can see nest doesn't understand it by default. – Konrad Oct 23 '22 at 16:35
  • https://stackoverflow.com/questions/6243051/how-to-pass-an-array-within-a-query-string – Konrad Oct 23 '22 at 16:36
  • Ok thanks, but in case I use the arrayParam[] notation, the query parameter I get on the backend is arrayParam[] instead of arrayParam which I define in a DTO. Is there a good way to avoid this? – mythic Oct 24 '22 at 07:15