Hapi Bookshelf Total Count
A Hapi plugin used with Bookshelf models to calculate the total number of records that match a query and appends it to the response. It can be used to calculate an absolute total count or a filtered total count.
Absolute Total Count
Appends the total_count
of all instances of the model when the query contains include[]=total_count
, regardless of query filter.
Register the Plugin
const Hapi = ; const server = ; server;
Configure the endpoint
const Bookshelf = config; const Book = BookshelfModel; server;
Request
$ curl -g GET "https://YOUR_DOMAIN/books?include[]=total_count"
Response
{
"data": [...],
"total_count": 100
}
Filtered Total Count
Appends the total_count
of a subset of model instances that match a query filter when the query contains include[]=total_count
. In order to calculate a filtered total_count
, you'll need to use this plugin in conjunction with hapi-query-filter and define a filter
function on each model that will be filtered. The model's filter
function is intended to be reused by the list endpoint.
Register the Plugin
const Hapi = ; const server = ; server;
Define a filter function on the model
// models/book.js const Bookshelf = config; moduleexports = BookshelfModel;
Configure the endpoint
const Book = ; server;
Request
$ curl -g GET "https://YOUR_DOMAIN/books?year=1984&include[]=total_count"
Response
{
"data": [...],
"total_count": 20
}
Approximate Total Count
Appends the approximate_count
which is a cached total count. Currently only Redis is supported as a cache. Both
requests that fetch the total_count
and approximate_count
will prime the cache.
Register the Plugin
const Bluebird = ;const Hapi = ;const Redis = ; Bluebird;Bluebird; const RedisClient = Redis; const server = ; server;
Define a filter function on the model
// models/book.js const Bookshelf = config; moduleexports = BookshelfModel;
Configure the endpoint
const Book = ; server;
include option - use this option to restrict counting to only the included items in the list
const Book = ; server;
Request
$ curl -g GET "https://YOUR_DOMAIN/books?year=1984&include[]=approximate_count"
Response
{
"data": [...],
"approximate_count": 20
}