Feature: #107104 - Introduce UrlFactory JavaScript module
See forge#107104
Description
TYPO3 already uses the native
URL and
URLSearch objects when
working with URLs. To make the generation of said objects easier, the module
@typo3/ is introduced.
Impact
URL and
URLSearch objects can be created by the factory's
create and
create methods.
The method
create creates a full
URL object while taking care
of setting its base automatically. The method accepts the following arguments:
url– stringparameters– mixed
Any value of
parameters, if not
undefined, will be handed to
create, being documented below.
The method
create creates a
URLSearch 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.
Note
When a nested object is passed, values of type null or undefined are discarded!
Examples
The following examples assume the existence of TYPO3.,
pointing to the route /custom_, while being on https:// for documentation purposes.
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
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
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
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
Note
Unlike
URLSearch's constructor,
Url does
not support JavaScript entries as
parameter argument. If this case is
required, entries can be converted into an object by using
Object..