node package manager
Orgs are free. Discover, share, and reuse code in your team. Create a free org »

hapi-footprints

hapi-footprints

Docs WIP

Some codes are borrowed from bedwetter, which is an alternative for hapi-footprints.

NPM

Usage

$ npm install hapi-footprints --save
// ES6 Syntax
import Footprints from 'hapi-footprints';

API

const footprints = new Footprints(options, overrideRoutes)

Creates a new instance of footprint.

  • options (Object) Optional
    • prefix (string)
      • Defaults to: /api
      • Prefix for the routes created by footprints
    • excludeModels (Array)
      • Defaults to: []
      • Example: ['user', 'post']
      • An array of model names to exclude from creating the routes.
    • excludeActions (Object)
      • Defaults to: {}
      • Example: {modelName: ['find', 'remove']}
      • An object for excluding a particular action or actions.
    • routeDefaults (Object)
      • Defaults to: {}
      • Example: {config: {tags: ['api']}}
      • An object which will be merged to every routes generated. Useful adding configurations for hapi.
    • cache (Object or false)
      • Defaults to:
        {
          cache: 'redisCache',
          expiresIn: 1000 * 60 * 5,
          segment: '!footprints',
          generateTimeout: 300,
        }
      • Disables cache when false, else configurations are passed down to hapi's server method's options. Caching is available for find, findCount, findOne actions. See here for more information about actions.
    • handler (Object)
      • See the comment-outs below for description of each keys available
      • Defaults to:
      {
        // name of handler to register
        name: 'footprints',
       
        // override default options of the handler
        options: {
          // will be deleted
          model: null,
       
          // enable cache for this footprint
          // works only on 'GET' method actions
          cache: true,
       
          // function to inject before executing a query to the database
          // could be used for caching the response, custom errors, etc.
          // it is injected before caching, therefore caching will not work.
          // NOTE: this option will not be executed in association routes
          // example: (query, options, callback) => { query.exec(callback) };
          injectBeforeQuery: false,
       
          // primaryKey of model, defaults to 'id' when set to false
          primaryKey: false,
       
          // paginations
          pagination: true,
       
          // default limits for 'find'
          limit: 30,
       
          // max limit for 'find'
          maxLimit: 30,
       
          // default offset
          offset: 0,
       
          // soft deletes
          softDelete: {
            // enable soft deletes
            enabled: true,
            // set attribute for soft deletes
            attr: 'deletedAt',
          },
       
          // population
          populateByDefault: true,
          populateLimit: 30,
       
          // associations
          child: {
            // primaryKey for the child model
            primaryKey: false,
          },
        },
      }
  • overrideRoutes (Object) Optional
    • Route configurations for specific route-actions.
    • Example:
      {
        modelName: {
          find: {
            // any hapi route configurations here,
            // but NOT "path" or "method", footprints will throw an error.
          },
          findCount: {},
          findOne: {},
          create: {},
          update: {},
          populate: {},
          populateWithId: {},
          populateCount: {},
          add: {},
          addWithId: {},
          destroy: {},
          remove: {},
        },
        // and so on...
      }

footprints.plugin()

Returns a plugin for hapi. See here for more about hapi's plugin.

Example

import hapi from 'hapi';
import dogwater from 'dogwater';
import models from './someModelFile.js';
import overrideRoutes from './someOtherFile.js';
 
const server = new Hapi.Server();
server.connection({ port: 3000 });
 
const footprints = new Footprints({
  // configurations for footprints...
}, overrideRoutes);
 
server.register([
  {
    register: dogwater,
    options: {
      models: models,
      // ... configurations for dogwater
    },
  },
  footprints.plugin(),
], (err) => {});
 
server.start(function () {
  console.log('Server running at:', server.info.uri);
});

Exposed by plugin

  • a handler, with a name passed in with options.handler.name
    • this handler is used for the actual route.handler, and can be used inside the overrideRoutes
  • a server method called cacheQuery, when options.cache is not disabled.
    • this server method is used for caching wateline model's query, by the criteria used in the query

Example of generated routes

  • GET /api/users

    • Action name: find
    • Find all users records
  • GET /api/users/count

    • Action name: findCount
    • Count all users records
  • GET /api/users/{id}

    • Action name: findOne
    • Find one user record
  • POST /api/users

    • Action name: create
    • Create a new user
  • POST, PATCH /api/users/{id}

    • Action name: update
    • Update user with {id}
  • GET /api/users/{id}/associatedModel

    • Action name: populate
    • Get all associated records for a user (records are associatedModel, in this case)
  • GET /api/users/{id}/associatedModel/{childId}

    • Action name: populateWithId
    • Get One associated record for user (associatedModel, in this case)
  • GET /api/users/{id}/associatedModel/count

    • Action name: populateCount
    • Count all associated records (count of associatedModels, in this case)
  • POST /api/users/{id}/associatedModel

    • Action name: add
    • Create a new associatedModel record, and adds a relation to the user with {id}
  • POST /api/users/{id}/associatedModel/{childId}

    • Action name: addWithId
    • Associates associatedModel with {childId}, with the user with {id}
  • DELETE /api/users/{id}

    • Action name: destroy
    • Deletes a user with {id}
  • DELETE /api/users/{id}/associatedModel/{childId}

    • Action name: remove
    • Removes association with {childId} from user with {id}

Run tests

$ npm test

License

MIT