UNPKG

@ragav-ks/xior-xray-plugin

Version:

A Xior plugin to capture all the API calls in AWS X-Ray traces.

40 lines (39 loc) 1.74 kB
import AWSXRay from 'aws-xray-sdk'; import { XiorError, } from 'xior'; export function xrayPlugin(options = {}) { return (adapter) => { return async (config) => { // Determine subsegment name: use custom serviceName or the request URL const subsegmentName = options.serviceName || (config.baseURL ?? 'Remote Server'); return await AWSXRay.captureAsyncFunc(subsegmentName, async (subsegment) => { if (subsegment) { // Mark this subsegment as a remote call subsegment.namespace = 'remote'; // Add annotations for logging/searching in X-Ray subsegment.addAnnotation('method', config.method || ''); subsegment.addAnnotation('baseUrl', config.baseURL || ''); subsegment.addAnnotation('path', config.url || ''); } try { // Perform the actual HTTP request const res = await adapter(config); subsegment?.addAnnotation('status', res.status); return res; } catch (err) { if (typeof err === 'string' || err instanceof Error) { if (err instanceof XiorError && err.response) { subsegment?.addAnnotation('status', err.response.status); } subsegment?.addError(err); } throw err; } finally { subsegment?.close(); } }, AWSXRay.getSegment()); }; }; } export default xrayPlugin;