UNPKG

@vtex/api

Version:
60 lines (59 loc) 2.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.metricDirectiveTypeDefs = exports.Metric = void 0; const graphql_1 = require("graphql"); const graphql_tools_1 = require("graphql-tools"); const __1 = require("../../../../../.."); class Metric extends graphql_tools_1.SchemaDirectiveVisitor { visitFieldDefinition(field) { const { resolve = graphql_1.defaultFieldResolver, name: fieldName } = field; const { name = `${__1.APP.NAME}-${fieldName}` } = this.args; field.resolve = async (root, args, ctx, info) => { let failedToResolve = false; let result = null; let ellapsed = [0, 0]; try { const start = process.hrtime(); result = await resolve(root, args, ctx, info); ellapsed = process.hrtime(start); } catch (error) { result = error; failedToResolve = true; } const status = failedToResolve ? 'error' : 'success'; ctx.graphql.status = status; const payload = { [status]: 1, }; // Legacy metrics (backward compatibility) metrics.batch(`graphql-metric-${name}`, failedToResolve ? undefined : ellapsed, payload); // New diagnostics metrics with stable names and attributes if (global.diagnosticsMetrics) { const attributes = { [__1.AttributeKeys.VTEX_ACCOUNT_NAME]: ctx.vtex.account, component: 'graphql', field_name: name, status, }; // Record latency histogram (record all requests, not just successful ones) global.diagnosticsMetrics.recordLatency(ellapsed, attributes); // Increment counter (status is an attribute, not in metric name) global.diagnosticsMetrics.incrementCounter('graphql_field_requests_total', 1, attributes); } else { console.warn('DiagnosticsMetrics not available. GraphQL field metrics not reported.'); } if (failedToResolve) { throw result; } return result; }; } } exports.Metric = Metric; exports.metricDirectiveTypeDefs = ` directive @metric ( name: String ) on FIELD_DEFINITION `;