CogentJS
A beautiful and elegant way to build urls for your REST API
This package helps you to quickly build urls for a REST API, using fluent syntax.
🔥 If you use Laravel - the defaults of this package will work with spatie/laravel-query-builder.
Basic usage
Make a url by calling the functions you need in a beautiful and elegant way:
// Importconst Query = ; // If custom configuration is required, see the Additional Configuration sectionconst query = ; // /posts?filter[name]=Bob&include=posts,comments&orderBy=-created_atconst url = query // the model you're selecting // where the models `name` is 'Bob' // include the models related relationships: posts and comments // order by -created_at desc ; // generate the url and pass it into fetch!
Installation
Npm
npm i cogent-js
Yarn
yarn add cogent-js
Additional Configuration
Base Url
You can optionally set the base_url
property when instantiating the class to automatically preprend the url to all urls:
const Query = ; const query = base_url: 'http://api.example.com'; // http://api.example.com/users?filter[name]=Bobconst url = query; // or .get();
Available Methods
where()
// /users?filter[name]=Bobconst url = query; // or .get();
whereIn()
// /users?filter[name]=bob,jerryconst url = query; // or .get();
select()
// /users?fields=name,age,date_of_birthconst url = query; // or .get();
includes()
// /users?include=postsconst url = query; // or .get();
appends()
// /users?append=full_name,ageconst url = query; // or .get();
limit()
// /users?limit=5const url = query; // or .get();
limit() | Pagination
// /users?page=2&limit=5const url = query; // or .get();
sort()
// /users?sort=-name,ageconst url = query; // or .get();
Custom parameters
If required, you can also append your own custom parameters to the url by passing an object to the params()
function.
// /users?format=adminconst url = query; // or .get();
Customizing Query Parameters
If you need to change the default values for the query parameters, you can optionally pass in a configuration object when initializing your query object.
const Query = ; const query = queryParameters: include: 'include_custom' filters: 'filter_custom' sort: 'sort_custom' fields: 'fields_custom' append: 'append_custom' page: 'page_custom' limit: 'limit_custom' ;
Contributing
Please see CONTRIBUTING for details.
Contact
Twitter @joelwmale