@fontoxml/fontoxml-development-tools
Version:
Development tools for Fonto.
66 lines (55 loc) • 1.45 kB
JavaScript
import chalk from 'chalk';
/** @typedef {import('../../src/getAppConfig.js').DevCmsConfig} DevCmsConfig */
/**
* @param {DevCmsConfig} config
*/
function configureDebugRouteHandler(config) {
return (req, res, next) => {
if (config.debugCms.includes(req.path)) {
next();
return;
}
const resWrite = res.write;
const resEnd = res.end;
const endpoint = req.path;
const chunks = [];
res.write = function (chunk) {
chunks.push(chunk);
resWrite.apply(res, arguments);
};
res.end = function (chunk, encoding) {
if (chunk) {
chunks.push(chunk);
}
res.end = resEnd;
res.end(chunk, encoding);
console.log('');
console.log(chalk.bold(req.method), chalk.bold(endpoint));
console.log(chalk.bold(' query:'), req.query);
console.log(chalk.bold(' body:'), req.body);
console.log(chalk.bold(' statusCode:'), res.statusCode);
if (res.get('etag')) {
console.log(chalk.bold(' eTag:'), res.get('etag'));
}
if (
res.get('content-type').indexOf('application/json') !== -1 &&
chunks.length
) {
let body = Buffer.concat(chunks).toString('utf8');
try {
body = JSON.parse(body);
if (body.content) {
body.content = `${body.content
.toString()
.substring(0, 15)}...`;
}
} catch (_error) {
// Do nothing
}
console.log(chalk.bold(' response:'), body);
}
};
next();
};
}
export default configureDebugRouteHandler;