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:
const { Query } = require("cogent-js");
const query = new Query();
const url = query
.for('posts')
.where('name', 'Bob')
.includes('posts', 'comments')
.orderBy('-created_at')
.get();
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 } = require('cogent-js');
const query = new Query({
base_url: 'http://api.example.com'
});
const url = query.for('users').where('name', 'Bob').url();
Available Methods
where()
const url = query.for('users').where('name', 'Bob').url();
whereIn()
const url = query.for('users').whereIn('name', ['bob', 'jerry']).url();
select()
const url = query.for('users').select('name', 'age', 'date_of_birth').url();
includes()
const url = query.for('users').includes('posts').url();
appends()
const url = query.for('users').appends('full_name', 'age').url();
limit()
const url = query.for('users').limit(5).url();
const url = query.for('users').limit(5).page(2).url();
sort()
const url = query.for('users').sort('-name', 'age').url();
Custom parameters
If required, you can also append your own custom parameters to the url by passing an object to the params()
function.
const url = query.for('users').params({ format: 'admin' }).url();
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 } = require("cogent-js");
const query = new 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