UNPKG

@graphql-mesh/plugin-statsd

Version:
70 lines (65 loc) 2.74 kB
'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } const StatsD = _interopDefault(require('hot-shots')); const statsd = require('@envelop/statsd'); const utils = require('@graphql-mesh/utils'); const metricNames = { delegationCount: 'delegations.count', delegationErrorCount: 'delegations.error.count', delegationLatency: 'delegations.latency', fetchCount: 'fetch.count', fetchErrorCount: 'fetch.error.count', fetchLatency: 'fetch.latency', }; function useMeshStatsd(pluginOptions) { const client = new StatsD(pluginOptions.client); const prefix = pluginOptions.prefix || 'graphql'; return { onPluginInit({ addPlugin }) { addPlugin(statsd.useStatsD({ ...pluginOptions, client, })); }, onFetch({ url, options, info }) { const tags = { url, method: options.method, sourceName: info === null || info === void 0 ? void 0 : info.sourceName, fieldName: info === null || info === void 0 ? void 0 : info.fieldName, requestHeaders: JSON.stringify(options.headers), }; const start = Date.now(); return ({ response }) => { tags.statusCode = response.status.toString(); tags.statusText = response.statusText; const responseHeadersObj = utils.getHeadersObj(response.headers); tags.responseHeaders = JSON.stringify(responseHeadersObj); client.increment(`${prefix}.${metricNames.fetchCount}`, tags); const end = Date.now(); if (!response.ok) { client.increment(`${prefix}.${metricNames.fetchErrorCount}`, tags); } client.histogram(`${prefix}.${metricNames.fetchLatency}`, end - start, tags); }; }, onDelegate({ sourceName, fieldName, args, key }) { const tags = { sourceName, fieldName, args: JSON.stringify(args), key, }; const start = Date.now(); return ({ result }) => { if (result instanceof Error) { client.increment(`${prefix}.${metricNames.delegationErrorCount}`, tags); } client.increment(`${prefix}.${metricNames.delegationCount}`, tags); const end = Date.now(); client.histogram(`${prefix}.${metricNames.delegationLatency}`, end - start, tags); }; }, }; } module.exports = useMeshStatsd;