UNPKG

heroku-debug

Version:
92 lines (75 loc) 3.31 kB
'use strict' var semver = require('semver') var debug = require('debug')('opbeat') var shimmer = require('../shimmer') module.exports = function (hapi, agent, version) { if (!semver.satisfies(version, '>=9.0.0')) { debug('hapi version %s not suppoted - aborting...', version) return hapi } debug('shimming hapi.Server.prototype.initialize') shimmer.wrap(hapi.Server.prototype, 'initialize', function (orig) { return function () { if (typeof this.ext === 'function') { this.ext('onPreAuth', function (request, reply) { debug('received Hapi onPreAuth event') // Record the fact that the preAuth extension have been called. This // info is useful later to know if this is a CORS preflight request // that is automatically handled by hapi (as those will not trigger // the onPreAuth extention) request.__opbeat_onPreAuth = true if (request.route) { // fingerprint was introduced in hapi 11 and is a little more // stable in case the param names change // - path example: /foo/{bar*2} // - fingerprint example: /foo/?/? var fingerprint = request.route.fingerprint || request.route.path if (fingerprint) { var name = (request.raw && request.raw.req && request.raw.req.method) || (request.route.method && request.route.method.toUpperCase()) if (typeof name === 'string') { name = name + ' ' + fingerprint } else { name = fingerprint } agent._instrumentation.setDefaultTransactionName(name) } } return reply.continue() }) this.ext('onPreResponse', function (request, reply) { debug('received Hapi onPreResponse event') // Detection of CORS preflight requests: // There is no easy way in hapi to get the matched route for a // CORS preflight request that matches any of the autogenerated // routes created by hapi when `cors: true`. The best solution is to // detect the request "fingerprint" using the magic if-sentence below // and group all those requests into on type of transaction if (!request.__opbeat_onPreAuth && request.route && request.route.path === '/{p*}' && request.raw && request.raw.req && request.raw.req.method === 'OPTIONS' && request.raw.req.headers['access-control-request-method']) { agent._instrumentation.setDefaultTransactionName('CORS preflight') } return reply.continue() }) } else { debug('unable to enable automatic Hapi transaction naming') } if (typeof this.on === 'function') { this.on('request-error', function (req, err) { if (req.raw && req.raw.req) { agent.captureError(err, { request: req.raw.req }) } else { debug('could not extract original request from hapi request') agent.captureError(err) } }) } else { debug('unable to enable Hapi error tracking') } return orig.apply(this, arguments) } }) return hapi }