UNPKG

@baselime/trpc-opentelemetry-middleware

Version:

Instrument your TRPC Application with OpenTelemetry

57 lines (54 loc) 1.93 kB
// src/index.ts import { trace } from "@opentelemetry/api"; import { experimental_standaloneMiddleware } from "@trpc/server"; // node_modules/flat/index.js function isBuffer(obj) { return obj && obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); } function keyIdentity(key) { return key; } function flatten(target, opts) { opts = opts || {}; const delimiter = opts.delimiter || "."; const maxDepth = opts.maxDepth; const transformKey = opts.transformKey || keyIdentity; const output = {}; function step(object, prev, currentDepth) { currentDepth = currentDepth || 1; Object.keys(object).forEach(function(key) { const value = object[key]; const isarray = opts.safe && Array.isArray(value); const type = Object.prototype.toString.call(value); const isbuffer = isBuffer(value); const isobject = type === "[object Object]" || type === "[object Array]"; const newKey = prev ? prev + delimiter + transformKey(key) : transformKey(key); if (!isarray && !isbuffer && isobject && Object.keys(value).length && (!opts.maxDepth || currentDepth < maxDepth)) { return step(value, newKey, currentDepth + 1); } output[newKey] = value; }); } step(target); return output; } // src/index.ts function tracing(options) { const tracer = trace.getTracer("@baselime/trpc"); options = options || {}; return experimental_standaloneMiddleware().create(async (opts) => { return tracer.startActiveSpan(`TRPC ${opts.type}`, async (span) => { const result = await opts.next(); if (options.collectInput && typeof opts.rawInput === "object") { span.setAttributes(flatten({ input: opts.rawInput })); } const meta = { path: opts.path, type: opts.type, ok: result.ok }; span.setAttributes(meta); span.end(); return result; }); }); } export { tracing };