Package Exports
- @innova2/url-builder
- @innova2/url-builder/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@innova2/url-builder) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Url-Builder
A lightweight library with many features to easy build URLs
Breaking changes from 1.x to 2.x :
UrlBuilder#addParam
does not replace existing param now. UseUrlBuilder#addOrReplaceParam
nowUrlBuilder#addParams
does not replace existing params now. UseUrlBuilder#addOrReplaceParams
nowUrlBuilder#addQueryParam
does not replace existing param now. UseUrlBuilder#addOrReplaceQueryParam
nowUrlBuilder#addQueryParams
does not replace existing params now. UseUrlBuilder#addOrReplaceQueryParams
now
π Features
This library allows :
- Create URLs most easly
- Parse and decompose your URLs
- Ride up in the URL tree
- Make comparisons between URLs
π οΈ Installation
To import the library you just need to run this command :
npm install @innova2/url-builder
π Usage
Create from existing URL
const url = UrlBuilder.createFromUrl('http://localhost:8080/users');
// or create new url with the constructor
Handle path
Add new path segment(s)
const userId = '170b16cd-ad47-4c9c-86cf-7c83bd40d775';
url.addPath(':id/comments').addParam('id', userId);
// Or
url.addPath(':id/comments', { id: userId });
Add multiples parameters after adding path segment(s)
const userId = '170b16cd-ad47-4c9c-86cf-7c83bd40d775';
const commentId = '218dd1c4-0bb0-425a-be0b-85427304e100';
url.addPath(':userId/comments/:commentId').addParams({ userId, commentId });
// Or
url.addPath(':userId/comments/:commentId', { userId, commentId });
If you want to add or replace existing param, use instead :
const userId = '170b16cd-ad47-4c9c-86cf-7c83bd40d775';
const commentId = '218dd1c4-0bb0-425a-be0b-85427304e100';
url.addPath(':userId/comments/:commentId')
.addParams({ userId: 3, commentId: 1 });
// Without replacement :
url.addParam('userId', userId);
// Param 'userId' is always : 3
// With replacement :
url.addOrReplaceParam('userId', userId);
// Param 'userId' is now : 170b16cd-ad47-4c9c-86cf-7c83bd40d775
// Or with multiples parameters
// Without replacement :
url.addParams({ userId: 10, commentId: 5 });
// Param 'userId' is always : 170b16cd-ad47-4c9c-86cf-7c83bd40d775
// Param 'commentId' is always : 1
// With replacement :
url.addOrReplaceParams({ userId: 10, commentId: 5 });
// Param 'userId' is now : 10
// Param 'commentId' is now : 5
Retrieve params
const url = new UrlBuilder()
.addParams({
startDate: '1679737680454',
endDate: '1679937680454',
});
const params = url.getParams();
// params contain all path params as Map
const filteredParams = url.findParams(([key, value]) => new Date(Number(value)).getDate() === 25);
// filteredParams contain a new Map only with param 'startDate'
Get the first path segment
const rowNum = 10;
const url = UrlBuilder.createFromUrl('http://localhost:8080/rows/:rowNum/cells').addParam('rowNum', rowNum);
url.getFirstPath(); // Output: 'rows'
Get the last path segment
url.getLastPath(); // Output: 'cells'
Handle query param
Add new query param
const page = 2;
url.addQueryParam('page', page);
Add multiples query params
const page = 2;
const order = 'DESC';
url.addQueryParams({ page, order });
If you want to add or replace existing query, use instead :
const page = 2;
const order = 'DESC';
url.addQueryParams({ page, order });
// Without replacement :
url.addQueryParam('page', 3);
// QueryParam 'page' is always : 2
// With replacement :
url.addOrReplaceQueryParam('page', 3);
// QueryParam 'page' is now : 3
// Or with multiples parameters
// Without replacement :
url.addQueryParams({ page: 4, order: 'ASC' });
// QueryParam 'page' is always : 3
// QueryParam 'order' is always : DESC
// With replacement :
url.addOrReplaceQueryParams({ page: 4, order: 'ASC' });
// QueryParam 'page' is now : 4
// QueryParam 'order' is now : ASC
Retrieve query params
const url = new UrlBuilder()
.addQueryParams({
style: 'dark',
utm_source: 'Google',
utm_medium: 'newsletter',
utm_campaign: 'summer',
isMobile: 1
});
const queryParams = url.getQueryParams();
// queryParams contain all query params as Map
const filteredQueryParams = url.findQueryParams(([key]) => key.startsWith('utm'));
// filteredQueryParams contain a new Map only with query params 'utm_source', 'utm_medium' and 'utm_campaign'
Handle file
Parse file in url
// Consider file part of path segments
const url = UrlBuilder.createFromUrl('http://localhost/users/10.html');
url.getRelativePath();
// Output : /users/10.html
url.getPathSegments();
// Output : ['users', '10.html'];
url.getFile();
// Output : undefined
// Consider file dissociated of path segments
const url2 = UrlBuilder.createFromUrl('http://localhost/users/10.html', true);
url2.getRelativePath();
// Output : /users/10.html
url2.getPathSegments();
// Output : ['users'];
url2.getFile();
// Output : { name: '10', ext: 'html' }
Define file
url.setFile({ name: 'mycover', ext: 'webp' });
url.getFile();
// Output : { name: 'mycover', ext: 'webp' }
Define file from filename
url.setFilename('mycover.webp');
url.getFile();
// Output : { name: 'mycover', ext: 'webp' }
Handle fragment
Parse fragment with url
const url = UrlBuilder.createFromUrl('http://localhost/users?page=1#foo');
url.getRelativePath(false, true);
// Output : /users#foo
// The first boolean is "withQuery" and the seconde is "withFragment"
// With query params and fragment :
url.getRelativePath(true, true);
// Output : /users?page=1#foo
Define fragment without hash
url.setFragment('bar');
Retrieve fragment
const fragment = url.getFragment();
// Output : bar
url.getRelativePath(false, true);
// Output : /users#bar
Merge path and query params
It's possible to merge path and query params with another url
const url = UrlBuilder.createFromUrl('http://localhost:3000').addPath('groups');
const anotherUrl = new UrlBuilder()
.addPath(':id/users', { id: 2 })
.addQueryParam('page', 1)
url.mergePathWith(anotherUrl).toString() // Get 'http://localhost:3000/groups/2/users?page=1'
Note : This function merge only path, params and query params with current url.
Work with parent
Get parent URL easly.
This function return a new instance of UrlBuilder
const url = UrlBuilder.createFromUrl('http://localhost:8080/orders/:orderId/products/:productId');
const parent = url.getParent(); // Get 'http://localhost:8080/orders/:orderId/products'
Or up to the specific level
url.getParent(3); // Get 'http://localhost:8080/orders'
Get relative path
Retrieve the relative path as string format
const postId = 'a937b39e-9664-404a-ac56-f3da2b83a951';
const url = UrlBuilder.createFromUrl('http://localhost:8080/posts/:id').addParam('id', postId);
url.getRelativePath(); // Output: '/posts/a937b39e-9664-404a-ac56-f3da2b83a951'
And with query params
Don't forget to add 'true' parameter to allow query params conversion
url.addQueryParam('displaySimilar', true);
url.getRelativePath(); // Output: '/posts/a937b39e-9664-404a-ac56-f3da2b83a951'
url.getRelativePath(true); // Output: '/posts/a937b39e-9664-404a-ac56-f3da2b83a951?displaySimilar=true'
Get query params as string
Retrieve the query params as string format
const url = UrlBuilder.createFromUrl('http://localhost:8080/vehicles').addQueryParams({
page: 2,
order: 'ASC',
});
url.getQueryString(); // Output: '?page=2&order=ASC'
Convert full URL to string
Retrieve the query params as string format
const name = 'url-builder';
const url = UrlBuilder.createFromUrl('https://github.com/InnovA2')
.addPath(':name/pulls')
.addParam('name', name);
url.toString(); // Output: 'https://github.com/InnovA2/url-builder/pulls'
π Advanced
Compare URL to another
Compare the current URL to another URL (UrlBuilder instance)
const id = '434f65eb-4e5f-4b29-899c-b3e159fff61c';
const id2 = '3e972ca2-b422-4ac9-b793-e6f305c7bfb2';
const url = UrlBuilder.createFromUrl('http://localhost:8080/users/:id').addParam('id', id);
const url2 = UrlBuilder.createFromUrl('http://localhost:8080/users/:id').addParam('id', id);
const url3 = UrlBuilder.createFromUrl('http://localhost:8080/users/:id').addParam('id', id2);
url.compareTo(url2); // Output: true
url.compareTo(url3); // Output: false
Compare relative path to another by segment
Compare the path segments of the current URL to another relative path
const url: UrlBuilder = UrlBuilder.createFromUrl('/users/10/comments');
url.compareToPathBySegment('/users/10/comments') // Output: true
const url2: UrlBuilder = UrlBuilder.createFromUrl('/users/:id/comments');
url2.compareToPathBySegment('/users/10/comments') // Output: false
const url3: UrlBuilder = UrlBuilder.createFromUrl('/users/:id/comments').addParam('id', 10);
url3.compareToPathBySegment('/users/10/comments') // Output: true
// Or, validate unfilled params
const url4: UrlBuilder = UrlBuilder.createFromUrl('/users/:id/comments');
url4.compareToPathBySegment('/users/10/comments', true) // Output: true
Get path between two segments
const url = UrlBuilder.createFromUrl('http://localhost:8080/users/10/comments');
url.getBetween2Segments('users', 'comments'); // Output: 10
const url2 = UrlBuilder.createFromUrl('http://localhost:8080/users/10/comments/5');
url2.getBetween2Segments('users', '5'); // Output: 10/comments
π Utils
Split path from string
Split path string by slash
UrlUtils.splitPath('/InnovA2/url-builder/pulls/'); // Output: ['InnovA2', 'url-builder', 'pulls']
// or if you have more slashes
UrlUtils.splitPath('/InnovA2///url-builder/pulls/'); // Output: ['InnovA2', 'url-builder', 'pulls']
Trim path from string
Trim path string by removing useless slashes
UrlUtils.trimPath('/InnovA2/url-builder/pulls/'); // Output: 'InnovA2/url-builder/pulls'
// or if you have more slashes
UrlUtils.trimPath('/InnovA2///url-builder/pulls/'); // Output: 'InnovA2/url-builder/pulls'
Parse filename
Parse filename to create file object containing 'name' and 'ext' (extension). Works with any extension (no verification).
UrlUtils.parseFile('image.png'); // Output: { name: 'image', ext: 'png' }
βοΈ API
Types / Interfaces
type ParamType = string | number | boolean;
type ParamFindPredicate = (value: [string, ParamType], index: number, obj: [string, ParamType][]) => boolean;
interface FileInterface {
name: string;
ext: string;
}
UrlBuilder
static createFromUrl(baseUrl: string): UrlBuilder
compareTo(url: UrlBuilder, relative = true): boolean
compareToPathBySegment(path: string, validateUnfilledParams = false): boolean
getScheme(): Scheme
setScheme(scheme: Scheme): UrlBuilder
getHost(): string
setHost(host: string): UrlBuilder
getPort(): numbe
setPort(port: number): UrlBuilder
getPathSegments(): string[]
setPathSegments(segments: string[], params?: Record<string, ParamType>): UrlBuilder
addPath(path: string, params?: Record<string, ParamType>): UrlBuilder
getParams(): Map<string, ParamType>
findParams(predicate: ParamFindPredicate): Map<string, ParamType>
setParams(params: Map<string, ParamType>): UrlBuilder
addParam(key: string, value: ParamType): UrlBuilder
addOrReplaceParam(key: string, value: ParamType): UrlBuilder
addParams(params: Record<string, ParamType>): UrlBuilder
addOrReplaceParams(params: Record<string, ParamType>): UrlBuilder
getQueryParams(): Map<string, ParamType>
findQueryParams(predicate: ParamFindPredicate): Map<string, ParamType>
setQueryParams(query: Map<string, ParamType>): UrlBuilder
addQueryParam(key: string, value: ParamType): UrlBuilder
addOrReplaceQueryParam(key: string, value: ParamType): UrlBuilder
addQueryParams(queries: Record<string, ParamType>): UrlBuilder
addOrReplaceQueryParams(queries: Record<string, ParamType>): UrlBuilder
setFilename(filename: string): UrlBuilder
setFile(file: FileInterface): UrlBuilder
getFile(): FileInterface
getFragment(): string
setFragment(fragment: string): UrlBuilder
mergePathWith(url: UrlBuilder): UrlBuilder
getFirstPathSegment(): string
getLastPathSegment(): string
getParent(n = 1): UrlBuilder
getBetween2Segments(a: string, b: string): string
getRelativePath(query = false, withFragment = false): string
getQueryString(): string
toString(): string
Note : Only the non-static getParent() method return new instance of UrlBuilder. Others update and return the current instance.
UrlUtils (namespace)
splitPath(path: string): string[]
trimPath(path: string): string
parseFile = (filename: string): FileInterface
βοΈ Licence
π₯ Authors
π€ Contributors
Do not hesitate to participate in the project! Contributors list will be displayed below.