Feature: #107104 - Introduce UrlFactory JavaScript module

See forge#107104

Description

TYPO3 already uses the native URL and URLSearchParams objects when working with URLs. To make the generation of said objects easier, the module @typo3/core/factory/url-factory.js is introduced.

Impact

URL and URLSearchParams objects can be created by the factory's createUrl and createSearchParams methods.

The method createUrl() creates a full URL object while taking care of setting its base automatically. The method accepts the following arguments:

  • url – string
  • parameters – mixed

Any value of parameters, if not undefined, will be handed to createSearchParams(), being documented below.

The method createSearchParams() creates a URLSearchParams object and accepts the following arguments:

  • parameters – mixed

Parameters can be passed as plain string values and nested objects. Passing a plain array is not supported.

Examples

The following examples assume the existence of TYPO3.settings.ajaxUrls.my_dedicated_endpoint, pointing to the route /custom_endpoint, while being on https://localhost for documentation purposes.

Create a simple URL object
import { UrlFactory } from '@typo3/core/factory/url-factory.js';

const url = UrlFactory.createUrl(TYPO3.settings.ajaxUrls.my_dedicated_endpoint);
console.log(url.toString()); // https://localhost/custom_endpoint
Copied!
Create a URL object containing a query string from a nested object
import { UrlFactory } from '@typo3/core/factory/url-factory.js';

const url = UrlFactory.createUrl(TYPO3.settings.ajaxUrls.my_dedicated_endpoint, {
  foo: 'bar',
  baz: {
    hello: 'world',
  },
});
console.log(url.toString()); // https://localhost/custom_endpoint?foo=bar&baz[hello]=world
Copied!
Create a URLSearchParams from a string input
import { UrlFactory } from '@typo3/core/factory/url-factory.js';

const urlSearchParams = UrlFactory.createSearchParams('foo=bar&baz=bencer');
console.log(urlSearchParams.toString()); // foo=bar&baz=bencer
Copied!
Create a URLSearchParams from an object input
import { UrlFactory } from '@typo3/core/factory/url-factory.js';

const urlSearchParams = UrlFactory.createSearchParams({foo: 'bar', baz: 'bencer'});
console.log(urlSearchParams.toString()); // foo=bar&baz=bencer
Copied!