DEV Community

Discussion on: Electron Adventures: Episode 3: What Can Backend Code Even Do?

Collapse
darrylnoakes profile image
Darryl Noakes • Edited on

RE: Query strings

You can use URLSearchParams.

let toQueryString = (params) => {
  return new URLSearchParams(params).toString();
}
Enter fullscreen mode Exit fullscreen mode
function appendSearchParams(
  url: string,
  params?: Record<string, string>
) {
  return url + "?" + toQueryString(params);
}
Enter fullscreen mode Exit fullscreen mode

I have this for one of my current projects:

function resolve(
  url: string | URL
  params?: Record<string, string>
) {
  const _url = new URL(url);
  new URLSearchParams(params).forEach((value, key) => {
    _url.searchParams.append(key, value);
  });
  return _url.toString();
}
Enter fullscreen mode Exit fullscreen mode

I use this because there is special handling by the URLSearchParams objects (e.g. the question mark in the URL). Also, it allows other operations on the Params and URL if necessary.

You could loop over the param object's entries manually, instead creating a URLSearchParams object and using forEach.
Using it seems more foolproof, so it's probably a good idea unless you need high performance.
Code:

function resolve(
  url: string | URL
  params?: Record<string, string>
) {
  const _url = new URL(url);
  if (params) {
    for (
      const [key, value] of Object.entries(params)
    ) {
      _url.searchParams.append(key, value);
    }
  }
  return _url.toString();
}
Enter fullscreen mode Exit fullscreen mode

The check on params is needed in because it is an optional parameter. I use a fuller form of this function for an internal API library, so a query string is not always required.
In JS, this check should be done anyway, in theory. In TS, simply make it a mandatory parameter.

Note: URL.searchParams is a read only instance of URLSearchParams.

MDN Docs:
URL
URLSearchParams

Collapse
taw profile image
Tomasz Wegrzanowski Author

Thanks, I didn't know about this.