Generate a request URL using backend javascript/typescript

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?

Answer №1

Yes, extracting key/value pairs from the input object with Object.entries(), filtering based on value presence, and then converting to a query string is essential for this task. Here's how you can achieve it:

class URLBuilder {
  user?: string
  category?: string
  page?: number
  limit?: number
  order?: string
}

function generateURL(userID: string, queryParams: URLBuilder) {
  const queryString = Object.entries({ userID, ...queryParams })
                            .filter(([,value]) => value)
                            .map(([key, value]) => `${key}=${value}`)
                            .join('&')
  
  return `https://custom-website.com/api/v1/content?${queryString}`
}

const finalURL = generateURL('123', {
  user: 'john_doe',
  category: 'technology'
})

console.log(finalURL) // https://custom-website.com/api/v1/content?userID=123&user=john_doe&category=technology"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the placeholder text of a textarea using a conditional statement in PHP

I currently have a textarea within a form that is being outputted: <textarea id='textarea' name='msg' rows='2' maxlength='255' cols='80' placeholder=' Share a thought...'></textarea> ...

Utilizing exported functions from an Angular factory or directive for future use

After completing my first web application using Angular.js, I incorporated a module to handle interactive graphics (specifically seat maps) with Raphael. This included creating directives for handling the Raphael functionality. angular.module('raphae ...

Searching for specific tags using PHP and JavaScript in MySQL: effective strategies to find what you're looking

What is the most efficient way to search for an item based on user-defined tags? Consider the following data: item | param ----------------- 1 | a 1 | b 1 | c 2 | b 2 | c 2 | d 3 | c 3 | d 3 ...

The rendering of graphs in FusionCharts is experiencing delays particularly in Internet Explorer, with Chrome performing more efficiently in comparison

I am currently utilizing FusionCharts to generate and display graphs. My requirement is to load over 60 graphs on a single page. Upon testing the page loading in Internet Explorer 11, it is taking approximately 5 minutes. However, when using Google Chrom ...

Tips for using AJAX and JSON to maintain real-time data in JSP pages

After hours of searching, I still couldn't find a simple solution to my problem. I need to make something easy. I have a Java class that contains a map of "Service" objects along with an integer variable called "lastCustomer". When this value changes ...

Modify mesh in three.js scene

Is there a way to dynamically change a mesh in a group triggered by a button click? I am loading an external .obj file: loader.load( obj, function ( object ) { createScene( object, mod.tipo, pid, cor.replace("#","0x") ); }); and adding it to a gro ...

Using Ajax to pass a dictionary of dictionaries

I'm currently developing a Django website and facing an issue with passing data from Javascript to Python using Ajax. Below is the code snippet: // Javascript file function myFunc() { {...} // Generate var 'values' which is a di ...

What is the proper way to retrieve the app object from a module in ExpressJS?

In my application, I am running an Express app by setting it up in the app.js file: var app = express(); Once the app is created, I can define variables like this: app.set('host', 'myhost') Now, within my project, I also have a sepa ...

Is the init-models.js file generated by sequelize-auto being used in my application to establish associations?

I am currently developing an express rest api using sequelize. After generating my models with the help of sequelize-auto (which created init-models.js), I have encountered an issue with utilizing associations in my tables. Although the associations are de ...

Discovering the vacant fields within a database by looping through them

My goal is to download a .pdf document from the external database Contentful by utilizing an HTML link on a user interface. The issue arises when certain fields inside Contentful do not always necessitate a pdf document. In these cases, the field remains ...

Assign characteristics to the initial four elements in the array, then repeat the process starting with the fifth element, followed by the ninth element, and so on

I've been working on a project using sanity.io. I retrieve data, store it in an array, and then send it to my front-end using express and ejs. Each post stored in the array will be represented as a card. These cards will have different css classes to ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

How can I use Jquery to animate an element to the right edge of the window?

Exploring the realm of jQuery animations, I am currently experimenting with animating a div to the right side of the window while changing its color using jQuery UI. This is just a fun project without any specific purpose in mind. Below is the code snippet ...

iOS Safari does not support equivalent regex unsupported lookbehind assertion

Trying to break a string into sentences using regex can be tricky. Unfortunately, the regex used in this example: var text = "Mr. Smith bought cheapsite.com for 1.5 million dollars, i.e. he paid a lot for it. Did he mind? Adam Jones Jr. thinks he didn ...

Troubleshooting IE Freezing Issue Due to JavaScript Code with .addClass and .removeClass

Need some help troubleshooting why my code is causing IE to crash. After commenting out sections, I discovered that the issue arises when using .addClass and/or .removeClass inside the if conditions: if ( percentExpenses > 50 && percentExpenses ...

What is the process for modifying the URL of a Silverlight application utilizing this approach?

Currently, I am in the process of creating a Silverlight application without ASP.NET. In my development, I am following a straightforward approach outlined here: However, upon compiling the application, the URL structure generated appears as www.mysite.c ...

Is there a way to output several lines from a JSON file in print form?

I'm working with HTML code that displays multiple lines from a JSON file, but it only shows one line at a time. How can I modify the code to display all users' information? <!DOCTYPE html> <html> <head> <script> function ...

Block users from viewing the image displayed within a JavaScript canvas

On my server, I have a path to an image that is accessed by a JavaScript to load the image onto a canvas. The script then proceeds to hide certain parts of the image using black layers. The issue arises when a user can easily view my JavaScript code, extr ...

Unable to capture data payload from POST request in ExpressJS

Hey there, I'm having an issue with my Express server. Everything seems to be working fine, but I'm not receiving data from the POST method. I have already installed and configured body-parser as well. const express = require("express") const ap ...

Can HTML/CSS be used to specifically target handheld mobile devices?

I am looking to optimize my video display in HTML by only showing it on desktop browsers. The difference in bandwidth between desktop and mobile devices is affecting the performance of mobile browsers, so I want to target only desktop users. Is there a way ...