|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const shimmer = require('../../datadog-shimmer') |
| 4 | +const { channel } = require('./helpers/instrument') |
| 5 | + |
| 6 | +const startChannel = channel('apm:fetch:request:start') |
| 7 | +const finishChannel = channel('apm:fetch:request:finish') |
| 8 | +const errorChannel = channel('apm:fetch:request:error') |
| 9 | + |
| 10 | +function wrapFetch (fetch, Request) { |
| 11 | + if (typeof fetch !== 'function') return fetch |
| 12 | + |
| 13 | + return function (input, init) { |
| 14 | + if (!startChannel.hasSubscribers) return fetch.apply(this, arguments) |
| 15 | + |
| 16 | + const req = new Request(input, init) |
| 17 | + const headers = req.headers |
| 18 | + const message = { req, headers } |
| 19 | + |
| 20 | + startChannel.publish(message) |
| 21 | + |
| 22 | + // Request object is read-only so we need new objects to change headers. |
| 23 | + arguments[0] = message.req |
| 24 | + arguments[1] = { headers: message.headers } |
| 25 | + |
| 26 | + return fetch.apply(this, arguments) |
| 27 | + .then( |
| 28 | + res => { |
| 29 | + finishChannel.publish({ req, res }) |
| 30 | + |
| 31 | + return res |
| 32 | + }, |
| 33 | + err => { |
| 34 | + if (err.name !== 'AbortError') { |
| 35 | + errorChannel.publish(err) |
| 36 | + } |
| 37 | + |
| 38 | + finishChannel.publish({ req }) |
| 39 | + |
| 40 | + throw err |
| 41 | + } |
| 42 | + ) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +if (globalThis.fetch) { |
| 47 | + globalThis.fetch = shimmer.wrap(fetch, wrapFetch(fetch, globalThis.Request)) |
| 48 | +} |
0 commit comments