Code coverage report for hapi-decorators/index.js

Statements: 100% (42 / 42)      Branches: 80% (8 / 10)      Functions: 100% (11 / 11)      Lines: 100% (42 / 42)      Ignored: none     

All files » hapi-decorators/ » index.js
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103    1 1 1                 1 2 2   2 2 2   2 1     1 1   1 1   1           1 1 1 1   1                 1       1     1 6     1 1 1           1       1   1 2 1     2 2 2         2   2 1   1       1 3        
'use strict'
 
var extend = require('extend')
var find = require('lodash.find')
var routeMethods = {
  get: 'get',
  post: 'post',
  put: 'put',
  delete: 'delete',
  patch: 'patch',
  all: '*'
}
 
exports.controller = function controller (baseUrl) {
  return function (target) {
    target.prototype.baseUrl = baseUrl
 
    target.prototype.routes = function () {
      var self = this
      var base = trimslash(this.baseUrl)
 
      if (!this.rawRoutes) {
        return []
      }
 
      return this.rawRoutes.map(function (route) {
        var url = (base + trimslash(route.path)) || '/'
 
        route.path = url
        route.config.bind = self
 
        return route
      })
    }
  }
}
 
function route (method, path) {
  return function (target, key, descriptor) {
    var targetName = target.constructor.name
    var routeId = targetName + '.' + key
 
    setRoute(target, key, {
      method: method,
      path: path,
      config: {
        id: routeId
      },
      handler: descriptor.value
    })
 
    return descriptor
  }
}
 
exports.route = route
 
// Export route aliases
Object.keys(routeMethods).forEach(function (key) {
  exports[key] = route.bind(null, routeMethods[key])
})
 
function validate (config) {
  return function (target, key, descriptor) {
    setRoute(target, key, {
      config: {
        validate: config
      }
    })
 
    return descriptor
  }
}
 
exports.validate = validate
 
function setRoute (target, key, value) {
  if (!target.rawRoutes) {
    target.rawRoutes = []
  }
 
  var targetName = target.constructor.name
  var routeId = targetName + '.' + key
  var defaultRoute = {
    config: {
      id: routeId
    }
  }
  var found = find(target.rawRoutes, 'config.id', routeId)
 
  if (found) {
    extend(true, found, value)
  } else {
    target.rawRoutes.push(extend(true, defaultRoute, value))
  }
}
 
function trimslash (s) {
  return s[s.length - 1] === '/'
    ? s.slice(0, s.length - 1)
    : s
}