Repository URL to install this package:
|
Version:
0.7.0 ▾
|
// (c) Copyright 2023 Supertenant Ltd. - all rights reserved.
// See LICENSE file in project root for license terms.
"use strict";const shimmer=require("shimmer"),methods=require("methods"),requireHook=require("../../../util/requireHook"),tracingUtil=require("../../tracingUtil"),httpServer=require("../protocols/httpServer"),cls=require("../../cls");let active=!1;function instrument(express){express.Router&&express.Router.handle&&express.Router.use&&(shimmer.wrap(express.Router,"handle",shimExpress4Handle),shimmer.wrap(express.Router,"use",shimExpress4Use)),express.Route&&express.Route.prototype&&methods.concat("all").forEach(method=>{"function"==typeof express.Route.prototype[method]&&shimmer.wrap(express.Route.prototype,method,shimHandlerRegistration)})}function shimExpress4Handle(realHandle){return function(){var args=[];for(let i=0;i<arguments.length;i++){var arg=arguments[i];args.push("function"==typeof arg?wrapExpress4HandleFn(arg):arg)}return realHandle.apply(this,args)}}function wrapExpress4HandleFn(fn){return function(err){return err&&err.message&&err.stack&&annotateHttpEntrySpanWithError(err),fn.apply(this,arguments)}}function shimExpress4Use(originalUse){return function(path,fn){if("string"!=typeof path||"function"!=typeof fn||4!==fn.length)return originalUse.apply(this,arguments);var args=[];for(let i=0;i<arguments.length;i++){var arg=arguments[i];args.push("function"==typeof arg?wrapExpress4ErrorHandlingFn(arg):arg)}return originalUse.apply(this,args)}}function wrapExpress4ErrorHandlingFn(fn){return function(err,req,res,next){return annotateHttpEntrySpanWithError(err),fn.apply(this,arguments)}}function annotateHttpEntrySpanWithError(err){var span;err&&active&&(span=cls.getCurrentEntrySpan())&&span.n===httpServer.spanName&&(span.data.http.error=tracingUtil.getErrorDetails(err))}function shimHandlerRegistration(original){return function(){var args=[];for(let i=0;i<arguments.length;i++){var arg=arguments[i];args.push("function"==typeof arg?wrapHandler(arg):arg)}return original.apply(this,args)}}function wrapHandler(fn){return fn.length<4?function(req,res,next){return annotateHttpEntrySpanWithPathTemplate(req),fn.apply(this,arguments)}:function(err,req,res,next){return annotateHttpEntrySpanWithPathTemplate(req),fn.apply(this,arguments)}}function annotateHttpEntrySpanWithPathTemplate(req){var span;req.route&&(span=cls.getCurrentEntrySpan())&&span.n===httpServer.spanName&&!span.pathTplFrozen&&(span.data.http.path_tpl=(req.baseUrl||"")+req.route.path)}exports.activate=function(){active=!0},exports.deactivate=function(){active=!1},exports.init=function(){requireHook.onModuleLoad("express",instrument)};