Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions src/middlewares/har.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,29 @@ export const HarMiddleware = (req: Request, res: Response, next: NextFunction) =
return originalSend.call(this, body);
};

res.once('finish', () => {
const HarEntry: Partial<Entry> = {
time: Date.now() - requestStartTime.getTime(),
startedDateTime: requestStartTimeStamp,
request: buildHarRequest(req),
response: buildHarResponse(res, { body: responseBody }),
}
res.once('finish', async () => {
try {
const mockId = res.locals.rq_metadata?.mockId;
// No matching mock (e.g. 404) means there's nothing to attach the log to.
if (!mockId) {
return;
}

const HarEntry: Partial<Entry> = {
time: Date.now() - requestStartTime.getTime(),
startedDateTime: requestStartTimeStamp,
request: buildHarRequest(req),
response: buildHarResponse(res, { body: responseBody }),
}

storageService.storeLog({ mockId: res.locals.rq_metadata.mockId, HarEntry, })
// Await so a rejected storeLog is caught here rather than surfacing
// as an unhandled rejection.
await storageService.storeLog({ mockId, HarEntry, })
} catch (error) {
// Never let a logging failure escape the finish handler — it would
// surface as an uncaught exception and can crash the process.
console.error("[HarMiddleware] Failed to store log", error);
}
});

next();
Expand Down
Loading