UNPKG

kobp

Version:
59 lines 2.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withJsonConfig = exports.withJson = void 0; const __1 = require(".."); const WithJson = () => { const config = { auditMessagePipeline: [], errorPipeline: [], suppressPath: `${process.env.KOBP_JSON_SILENT_PATH || ''}` || '/healthcheck' }; const middleware = () => { // Assign logger if needed. const suppressPathPattern = new RegExp(config.suppressPath, 'i'); return async function (ctx, next) { const url = ctx.request.url; const loggy = suppressPathPattern.test(url) ? null : __1.Loggy.current(); const auditMessage = (event, error) => { const httpStatus = event === 'start' ? '' : `${ctx.response?.status || ''}`; let msg = `${ctx.request.method} ${url} ${httpStatus}`; for (const pipe of config.auditMessagePipeline || []) { msg = pipe(msg, event, ctx, error); } return msg; }; try { loggy?.log(`[<<] ${auditMessage('start')}`); await next(); loggy?.success(`[>>] ${auditMessage('success')}`); } catch (err) { // will only respond with JSON let _err = err; if (config.errorPipeline) { for (const pipe of config.errorPipeline) { _err = pipe(_err, loggy); } } ctx.status = _err.statusCode || _err.status || 500; ctx.body = { success: false, code: _err.code && _err.code, error: _err.message, data: _err.data, type: _err instanceof __1.KobpError ? 'kobp' : undefined, }; // Always logs error case loggy?.failed(`[>>] ${auditMessage('error', _err)}`, _err); } }; }; return { config, middleware, }; }; const instance = WithJson(); exports.withJson = instance.middleware; exports.withJsonConfig = instance.config; //# sourceMappingURL=withJson.js.map