npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

hapi-bookshelf-total-count

v4.3.0

Published

Hapi plugin used with Bookshelf models to calculate the total number of records that match a query and appends it to the response

Downloads

58

Readme

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 = require('hapi');

const server = new Hapi.Server();

server.register([
  require('hapi-bookshelf-total-count')
], (err) => {

});

Configure the endpoint

const Bookshelf = require('bookshelf')(require('knex')(config));

const Book = Bookshelf.Model.extend({ tableName: 'books' });

server.route({
  method: 'GET',
  path: '/books',
  config: {
    plugins: {
      totalCount: { model: Book }
    },
    handler: (request, reply) => {
      return new Book().fetchAll()
      .then((books) => {
        reply({ data: books });
      });
    }
  }
});

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 = require('hapi');

const server = new Hapi.Server();

server.register([
  require('hapi-bookshelf-total-count'),
  {
    register: require('hapi-query-filter'),
    options: { ignoredKeys: ['include'] }
  }
], (err) => {

});

Define a filter function on the model

// models/book.js

const Bookshelf = require('bookshelf')(require('knex')(config));

module.exports = Bookshelf.Model.extend({
  tableName: 'books'
  /**
   * @param {Object} filter - from request.query.filter
   * @param {Object} [credentials] - from request.auth.credentials
   * You may add any additional parameters after filter and credentials
   */
  filter: function (filter, credentials) {
    return this.query((qb) => {
      qb.where('deleted', false);

      if (filter.year) {
        qb.where('year', filter.year);
      }
    });
  }
});

Configure the endpoint

const Book = require('../models/book');

server.route({
  method: 'GET',
  path: '/books',
  config: {
    plugins: {
      queryFilter: { enabled: true },
      totalCount: { model: Book }
    },
    handler: (request, reply) => {
      return new Book().filter(request.query.filter, request.auth.credentials)
      .fetchAll()
      .then((books) => {
        reply({ data: books });
      });
    }
  }
});

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 = require('bluebird');
const Hapi     = require('hapi');
const Redis    = require('redis');

Bluebird.promisifyAll(Redis.RedisClient.prototype);
Bluebird.promisifyAll(Redis.Multi.prototype);

const RedisClient = Redis.createClient({
  port: '6379',
  host: 'localhost'
});

const server = new Hapi.Server();

server.register([
  {
    register: require('hapi-bookshelf-total-count'),
    options: {
      redisClient: RedisClient,
      ttl: (count) => count / 10, // a function which returns the TTL to set for the cached approximate count
      uniqueKey: (request) => request.auth.credentials.api_key // an optional function to add additional uniqueness to the cache key
    }
  }
], (err) => {

});

Define a filter function on the model

// models/book.js

const Bookshelf = require('bookshelf')(require('knex')(config));

module.exports = Bookshelf.Model.extend({
  tableName: 'books'
  /**
   * @param {Object} filter - from request.query.filter
   * @param {Object} [credentials] - from request.auth.credentials
   * You may add any additional parameters after filter and credentials
   */
  filter: function (filter, credentials) {
    return this.query((qb) => {
      qb.where('deleted', false);

      if (filter.year) {
        qb.where('year', filter.year);
      }
    });
  }
});

Configure the endpoint

const Book = require('../models/book');

server.route({
  method: 'GET',
  path: '/books',
  config: {
    plugins: {
      queryFilter: { enabled: true },
      totalCount: { model: Book }
    },
    handler: (request, reply) => {
      return new Book().filter(request.query.filter, request.auth.credentials)
      .fetchAll()
      .then((books) => {
        reply({ data: books });
      });
    }
  }
});

include option - use this option to restrict counting to only the included items in the list

const Book = require('../models/book');

server.route({
  method: 'GET',
  path: '/books',
  config: {
    plugins: {
      queryFilter: { enabled: true },
      totalCount: { 
        include: ['approximate'],
        model: Book 
      }
    },
    handler: (request, reply) => {
      return new Book().filter(request.query.filter, request.auth.credentials)
      .fetchAll()
      .then((books) => {
        reply({ data: books });
      });
    }
  }
});

Request

$ curl -g GET "https://YOUR_DOMAIN/books?year=1984&include[]=approximate_count"

Response

{
  "data": [...],
  "approximate_count": 20
}