const axios = require('axios'); import { NextFunction, Request, Response, Router } from 'express'; import {getPdConfig} from './pd-config-builder'; /** * To trigger PD with max 5 retires * @notes We are not going to wait for the PD to get trigger, hence you can't await on it. * @sync * @stable * @param err * @param req * @param status */ export const triggerPd = (err: any, req: Request, status: any) => { trigger(err, req, 0); }; const trimKey = (value: any): string => typeof value === 'string' ? value.trim() : ''; const trigger = (error: any, req: any, reTryCount: number) => { const { pdServiceKey } = getPdConfig() || { pdServiceKey: '' }; const serviceKey = trimKey(pdServiceKey); if (!serviceKey) { return; } const { hostname, message, response, stack, code } = error; const userInfo = { client: req.headers.client, username: req.headers.username }; const json = { service_key: serviceKey, event_type: 'trigger', description: 'FAILURE: for ' + req.method + req.originalUrl + ' on ' + req.hostname, details: { userInfo, hostname, message, response, response_data: (response || {}).data, response_body: (response || {}).body, stack, code } }; if (reTryCount > 5) { console.log(`Retried of ${reTryCount}, but failed`); return; } console.log(json); axios .post('https://events.pagerduty.com/generic/2010-04-15/create_event.json', json) .then(() => { console.log('PD triggered successfully'); }) .catch((err: any) => { console.log('Error in triggering the PD'); console.log(err); console.log('Retrying', reTryCount++); trigger(json, req, reTryCount + 1); }); };