import { IncidentClient, Severity } from '@oppex-dev/integration-sdk'; import { Request } from 'express'; import { getOppexConfig } from './oppex-config-builder'; let client: any = null; // Mirrors the SDK's own constructor validation: a non-empty trimmed string // passes through, blank/whitespace becomes null ("no service key"), undefined // stays undefined, anything else becomes null rather than being forwarded as-is. const trimKey = (value: any): string => typeof value === 'string' ? value.trim() : ''; const getOppexServiceKey = (serviceKey: any): string | null | undefined => { if (typeof serviceKey === 'string') { const trimmed = serviceKey.trim(); return trimmed.length ? trimmed : null; } if (serviceKey === undefined) return undefined; return null; }; /** * To trigger Oppex with max 5 retires * @notes Unlike triggerPd, this never runs a manual retry loop -- IncidentClient * already retries internally, so there's no need to carry over triggerPd's own * (buggy) manual retry, which rebuilds its payload from the wrong shape on every * retry attempt. * @notes We are not going to wait for Oppex to get trigger, hence you can't await on it. * @sync * @stable * @param err * @param req * @param status */ export const triggerOppex = (err: any, req: Request, status: any) => { const { oppexApiKey, oppexServiceKey } = getOppexConfig() || {}; const apiKey = trimKey(oppexApiKey); if (!apiKey) { return; } if (!client) { try { client = new IncidentClient({ apiKey, serviceKey: getOppexServiceKey(oppexServiceKey) || null }); } catch (constructErr) { console.log('Failed to construct Oppex IncidentClient'); console.log(constructErr); return; } } const { hostname, message, response, stack, code } = err; const userInfo = { client: req.headers.client, username: req.headers.username }; client.sendIncidentAsync({ title: 'FAILURE: for ' + req.method + req.originalUrl + ' on ' + req.hostname, source: req.hostname, severity: status === 408 ? Severity.MEDIUM : Severity.HIGH, details: JSON.stringify({ userInfo, hostname, message, response, response_data: (response || {}).data, response_body: (response || {}).body, stack, code }) }); };