The spatie
function is a URL builder that allows you to easily add query parameters to a URL using a fluent interface compatible with spatie/laravel-query-builder.
You can install package using yarn (or npm):
yarn add @limitless.claver/laravel-query-builder
To use the spatie
function, simply call it with a URL string as its argument. The returned object has three
methods: filter
, include
, and sort
, which can be chained together to build the desired URL.
const {spatie} = require("@limitless.claver/laravel-query-builder");
const url = 'https://example.com';
const result = spatie(url)
.filter('status', 'published')
.include('author', 'categories')
.sort('title', '-date')
.build();
console.log(result);
// Outputs: https://example.com?filter[status]=published&include=author,categories&sort=title,-date
Adds a filter query parameter to the URL. The key
argument is the name of the filter, and the value
argument is the value of the filter.
If the URL already has query parameters, the filter is added with an ampersand (&
) separator. Otherwise, the filter is added with a question mark (?
) separator.
Example:
const url = 'https://example.com/posts';
const result = spatie(url)
.filter('status', 'published')
.build();
console.log(result);
// Outputs: https://example.com/posts?filter[status]=published
Adds an include query parameter to the URL. The value
argument can be a string or an array of strings.
If the URL already has an include parameter, the new values are appended to the existing ones. Otherwise, a new include parameter is added.
Example:
const url = 'https://example.com/posts';
const result = spatie(url)
.include('author', 'categories')
.build();
console.log(result);
// Outputs: https://example.com/posts?include=author,categories
Adds a sort query parameter to the URL. The field
argument can be a string or an array of strings.
If the URL already has a sort parameter, the new values are appended to the existing ones. Otherwise, a new sort parameter is added.
Example:
const url = 'https://example.com/posts';
const result = spatie(url)
.sort('title', '-date')
.build();
console.log(result);
// Outputs: https://example.com/posts?sort=title,-date
Adds a query parameter to the URL. The condition
argument must be a boolean.
And the callback
should would return an interface for further chaining or building.
Example
const url = 'https://example.com/posts';
const result = spatie(url).include('author')
.when('claver'.length > 5, q => q.sort('-title'))
.sort('name')
.filter("status","Published").build()
console.log(result);
// Outputs: https://example.com/posts?include=author&sort=-title,name&filter[status]=Published
Returns the built URL string.
Example
const url = 'https://example.com/posts';
const result = spatie(url)
.filter('status', 'published')
.include('author', 'categories')
.sort('title', '-date')
.build();
console.log(result);
// Outputs: https://example.com/posts?filter[status]=published&include=author,categories&sort=title,-date