all files / core/lib/ hooks.js

100% Statements 25/25
100% Branches 6/6
100% Functions 4/4
100% Lines 24/24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                            170× 170× 170×                 1666×                   215× 215× 215×   215× 189×     215×                   1451× 1451×   218× 218×   218× 218× 218×          
 
'use strict'
 
let debug = require('debug')('mako:hooks')
let Emitter = require('events')
let flatten = require('array-flatten')
let Plugins = require('./plugins')
let Promise = require('bluebird')
let utils = require('mako-utils')
 
/**
 * A helper class for managing and running hooks.
 *
 * @class
 */
class Hooks extends Emitter {
  /**
   * Creates a new instance.
   */
  constructor () {
    debug('initialize')
    super()
    this.handlers = new Map()
  }
 
  /**
   * Generate a key from the given arguments.
   *
   * @return {String}
   */
  key () {
    return flatten.from(arguments).join('-')
  }
 
  /**
   * Adds a single `handler` for the given `action` and `type`.
   *
   * @param {String} key        The hook key.
   * @param {Function} handler  The handler fn.
   */
  add (key, handler) {
    let name = handler.name || '(unnamed)'
    let id = this.key(key)
    debug('%s add %s', id, name)
 
    if (!this.handlers.has(id)) {
      this.handlers.set(id, new Plugins(id))
    }
 
    this.handlers.get(id).use(handler)
  }
 
  /**
   * Runs the given handlers for the given `action` and `type`.
   *
   * @param {String} hook  The hook key.
   * @return {Promise}
   */
  run (hook, args) {
    let key = this.key(hook)
    if (!this.handlers.has(key)) return Promise.resolve()
 
    let plugins = this.handlers.get(key)
    let timer = utils.timer()
 
    debug('running %s', key)
    return plugins.run(args)
      .finally(() => debug('ran %s (took %s)', key, timer()))
  }
}
 
// single export
module.exports = Hooks