kobp
Version:
Koa Boilerplate with MikroORM
56 lines • 2.17 kB
JavaScript
import { KobpError, Loggy } from '..';
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 : 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 KobpError ? 'kobp' : undefined,
};
// Always logs error case
loggy?.failed(`[>>] ${auditMessage('error', _err)}`, _err);
}
};
};
return {
config,
middleware,
};
};
const instance = WithJson();
export const withJson = instance.middleware;
export const withJsonConfig = instance.config;
//# sourceMappingURL=withJson.js.map