0

I am using this boilerplate for my api.

I have the following route: GET /questions

In this route I wan't to dynamically get the relations in the data, for example GET /questions?relations=user?relations=answer. This works just fine, but when I wan't only one relation, for example GET /questions?relations=user I get the following error:

{
    "name": "ParameterParseJsonError",
    "message": "Given parameter relations is invalid. Value (\"user\") cannot be parsed into JSON.",
    "errors": []
}

Here is the request:

@Get()
public find(@QueryParam('relations') relations: string[]): Promise<Question[]> {
    return this.questionService.find(relations);
}

The problem seems to be, that it recognizes the query param as a string and not a string array and therefore can't cast it into an array. My next idea was to make an union type like the following:

public find(@QueryParam('relations') relations: string[] | string): Promise<Question[]> {
    let _relations: string[] = [];
    if (typeof relations === 'string') {
        _relations.push(relations);
    } else {
        _relations = relations;
    }
    return this.questionService.find(_relations);
}

This still doesn't solve my problem. When I make a request with one relation I still get the same error. How can I solve this?

Gion Rubitschung
  • 741
  • 11
  • 31

1 Answers1

1

Well I found the solution and it's quite bohering me that I didn't come to this solution earlier. If you send the request like the following: GET /question?relations=user, the value is send with as a string. At the point you send a second value, the query becomes an array. To properly tell that the query is an array, you can do the following: GET /questions?relations[]=user. I didn't use this, because I thought GET /questions?relations=user was standard.

Gion Rubitschung
  • 741
  • 11
  • 31