Is there a more efficient way to construct the request URL without using if-else statements?
I am attempting to generate a URL for a request to another service. There are 5 parameters, with one being mandatory and the other four optional.
For example:
https://web-site.com/v1/assets?author=${id}&category=cat&page=1&per-page=1&sort=abc
author
is the mandatory parameter. The rest can be passed independently.
Examples:
https://web-site.com/v1/assets?author=${id}&category=cat&page=1&per-page=1&sort=abc
https://web-site.com/v1/assets?author=${id}&per-page=1&sort=abc
https://web-site.com/v1/assets?author=${id}&sort=abc
https://web-site.com/v1/assets?author=${id}&category=cat&sort=abc
https://web-site.com/v1/assets?author=${id}&category=cat
I am working on building the URL in this manner:
import { QueryDto } from '../types/dtos/query.dto'
export function urlComposer(id: string, query: QueryDto) {
const params = Object.entries(query)
.filter(([key, value]) => value !== undefined && key !== 'author')
.map(([key, value]) => `${key}=${value}`)
.join('&');
return `https://web-site.com/v1/assets?author=${id}&${params}`;
}
QueryDto.ts
import { ApiProperty } from '@nestjs/swagger'
export class QueryDto {
@ApiProperty()
author: string
@ApiProperty({required: false})
category?: string
@ApiProperty({required: false})
page?: number
@ApiProperty({required: false})
perPage?: number
@ApiProperty({required: false})
sort?: string
}
I believe there is a simpler approach to constructing such URLs dynamically. Do you have any suggestions or solutions of your own?