This commit is contained in:
seb
2026-07-31 18:20:54 +02:00
parent 63df454861
commit 1a05a5b7d6
5 changed files with 529 additions and 20 deletions

View File

@@ -1,19 +1,54 @@
import chalk from 'chalk';
export const loggerMiddleware = (req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
const method = chalk.bold.blue(req.method.padEnd(7));
const url = req.originalUrl;
let status = res.statusCode;
if (status >= 500) status = chalk.red(status);
else if (status >= 400) status = chalk.yellow(status);
else if (status >= 300) status = chalk.cyan(status);
else status = chalk.green(status);
function safeJson(value) {
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
console.log(`${method} ${url} ${status} ${chalk.gray(`(${duration}ms)`)}`);
});
next();
function captureResponseBody(res) {
let body;
const originalJson = res.json.bind(res);
const originalSend = res.send.bind(res);
res.json = (payload) => {
body = payload;
return originalJson(payload);
};
res.send = (payload) => {
if (body === undefined) {
body = payload;
}
return originalSend(payload);
};
return () => body;
}
export const loggerMiddleware = (req, res, next) => {
const start = Date.now();
const getBody = captureResponseBody(res);
res.on('finish', () => {
const duration = Date.now() - start;
const method = chalk.bold.blue(req.method.padEnd(7));
const url = req.originalUrl;
let status = res.statusCode;
if (status >= 500) status = chalk.red(status);
else if (status >= 400) status = chalk.yellow(status);
else if (status >= 300) status = chalk.cyan(status);
else status = chalk.green(status);
console.log(`${method} ${url} ${status} ${chalk.gray(`(${duration}ms)`)}`);
console.log(chalk.gray(' params:'), safeJson(req.params ?? {}));
console.log(chalk.gray(' query:'), safeJson(req.query ?? {}));
console.log(chalk.gray(' body:'), safeJson(req.body ?? {}));
console.log(chalk.gray(' response:'), safeJson(getBody()));
});
next();
};

View File

@@ -56,8 +56,8 @@ export function register(app, basePath = '') {
/**
* @route GET /article/:sku
* @description Returns an article by SKU if the user may access its category.
* @returns {Object} 200 - `{ article }`
* @description Returns article detail by SKU if the user may access its category.
* @returns {Object} 200 - `{ article }` detail shape (`unit`, `brand`, `categoryIds`, `photos`, `eans`, `prices`, …)
*/
app.get(`${basePath}/article/:sku`, async (req, res) => {
const sku = typeof req.params.sku === 'string' ? req.params.sku.trim() : '';
@@ -77,9 +77,9 @@ export function register(app, basePath = '') {
/**
* @route PATCH /article/:sku
* @description Updates an article name by SKU if the user may access its category.
* @description Updates an article name by SKU; returns the same detail shape as GET.
* @body {string} name
* @returns {Object} 200 - `{ article }`
* @returns {Object} 200 - `{ article }` detail shape
*/
app.patch(`${basePath}/article/:sku`, async (req, res) => {
const sku = typeof req.params.sku === 'string' ? req.params.sku.trim() : '';

View File

@@ -1,3 +1,4 @@
import chalk from 'chalk';
import sql from 'mssql';
import LibDashStore from 'libdashstore';
import env from '../config/env.js';
@@ -6,6 +7,61 @@ let pool;
let store;
let connecting;
const STORE_NAMESPACES = [
'companyuser',
'company',
'category',
'article',
'lang',
'tax',
'google_auth',
];
/**
* Wraps LibDashStore namespace methods so each call logs its duration.
* @param {InstanceType<typeof LibDashStore>} rawStore
* @returns {InstanceType<typeof LibDashStore>}
*/
function wrapStoreWithTiming(rawStore) {
for (const namespace of STORE_NAMESPACES) {
const api = rawStore[namespace];
if (!api || typeof api !== 'object') continue;
for (const [method, fn] of Object.entries(api)) {
if (typeof fn !== 'function') continue;
api[method] = async (...args) => {
const start = Date.now();
try {
return await fn(...args);
} finally {
const duration = Date.now() - start;
console.log(
`${chalk.magenta('libstore')} ${namespace}.${method} ${chalk.gray(`(${duration}ms)`)}`
);
}
};
}
}
for (const method of ['purge']) {
const fn = rawStore[method];
if (typeof fn !== 'function') continue;
rawStore[method] = async (...args) => {
const start = Date.now();
try {
return await fn(...args);
} finally {
const duration = Date.now() - start;
console.log(`${chalk.magenta('libstore')} ${method} ${chalk.gray(`(${duration}ms)`)}`);
}
};
}
return rawStore;
}
function getMssqlConfig() {
const { server, database, user, password, port, encrypt, trustServerCertificate } = env.mssql;
@@ -43,7 +99,7 @@ export async function getStore() {
if (!connecting) {
connecting = (async () => {
pool = await new sql.ConnectionPool(getMssqlConfig()).connect();
store = await new LibDashStore(pool);
store = wrapStoreWithTiming(await new LibDashStore(pool));
return store;
})().finally(() => {
connecting = undefined;