-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmiddlewares.ts
30 lines (28 loc) · 990 Bytes
/
middlewares.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { getRequestId } from '@/shared/app/app-request-context';
import { Action, CommandHandler, EventHandler } from '@/shared/cqrs/bus.types';
import { FastifyBaseLogger } from 'fastify';
export function decorateWithMetadata(
action: Action<unknown>,
handler: CommandHandler | EventHandler,
) {
action.meta = {
...action.meta,
correlationId: action.meta?.correlationId || getRequestId(),
timestamp: action.meta?.timestamp || Date.now(),
};
return handler(action) as Promise<CommandHandler | EventHandler>;
}
export function makeTrackExecutionTime(logger: FastifyBaseLogger) {
return async function trackExecutionTime(
action: Action<unknown>,
handler: CommandHandler | EventHandler,
) {
const startTime = performance.now();
const result = await handler(action);
const endTime = performance.now();
logger.info(
`Action ${action.type} took ${(endTime - startTime).toFixed(2)}ms of execution time.`,
);
return result;
};
}