| 30 | import { Request } from 'express'; |
| 31 | |
| 32 | class ExpressPlugin implements SwPlugin { |
| 33 | readonly module = 'express'; |
| 34 | readonly versions = '*'; |
| 35 | |
| 36 | install(installer: PluginInstaller): void { |
| 37 | this.interceptServerRequest(installer); |
| 38 | } |
| 39 | |
| 40 | private interceptServerRequest(installer: PluginInstaller) { |
| 41 | const express = installer.require?.('express') ?? require('express'); |
| 42 | const router = express.Router ?? installer.require?.('express/lib/router') ?? require('express/lib/router'); |
| 43 | const _handle = router.handle; |
| 44 | |
| 45 | router.handle = function (req: Request, res: ServerResponse, next: any) { |
| 46 | const carrier = ContextCarrier.from((req as any).headers || {}); |
| 47 | const reqMethod = req.method ?? 'GET'; |
| 48 | const operation = reqMethod + ':' + (req.originalUrl || req.url || '/').replace(/\?.*/g, ''); |
| 49 | const span = ignoreHttpMethodCheck(reqMethod) |
| 50 | ? DummySpan.create() |
| 51 | : ContextManager.current.newEntrySpan(operation, carrier, [Component.HTTP_SERVER, Component.EXPRESS]); |
| 52 | |
| 53 | span.component = Component.EXPRESS; |
| 54 | |
| 55 | if (span.depth) |
| 56 | // if we inherited from http then just change component ID and let http do the work |
| 57 | return _handle.apply(this, arguments); |
| 58 | |
| 59 | return HttpPlugin.wrapHttpResponse(span, req, res, () => { |
| 60 | // http plugin disabled, we use its mechanism anyway |
| 61 | try { |
| 62 | return _handle.call(this, req, res, (err: Error) => { |
| 63 | span.error(err); |
| 64 | next.call(this, err); |
| 65 | }); |
| 66 | } finally { |
| 67 | // req.protocol is only possibly available after call to _handle() |
| 68 | span.tag( |
| 69 | Tag.httpURL( |
| 70 | ((req as any).protocol ? (req as any).protocol + '://' : '') + (req.headers.host || '') + req.url, |
| 71 | ), |
| 72 | ); |
| 73 | } |
| 74 | }); |
| 75 | }; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | // noinspection JSUnusedGlobalSymbols |
| 80 | export default new ExpressPlugin(); |
nothing calls this directly
no outgoing calls
no test coverage detected