chore(api): clean up index file
This commit is contained in:
16
apps/api/src/hooks/request-id.hook.ts
Normal file
16
apps/api/src/hooks/request-id.hook.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import type {
|
||||
FastifyReply,
|
||||
FastifyRequest,
|
||||
HookHandlerDoneFunction,
|
||||
} from 'fastify';
|
||||
|
||||
export function requestIdHook(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
done: HookHandlerDoneFunction,
|
||||
) {
|
||||
if (!request.headers['request-id']) {
|
||||
request.headers['request-id'] = request.id;
|
||||
}
|
||||
done();
|
||||
}
|
||||
58
apps/api/src/hooks/request-logging.hook.ts
Normal file
58
apps/api/src/hooks/request-logging.hook.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import type {
|
||||
FastifyReply,
|
||||
FastifyRequest,
|
||||
HookHandlerDoneFunction,
|
||||
} from 'fastify';
|
||||
import { path, pick } from 'ramda';
|
||||
|
||||
const ignoreLog = ['/healthcheck', '/metrics', '/misc'];
|
||||
const ignoreMethods = ['OPTIONS'];
|
||||
|
||||
const getTrpcInput = (
|
||||
request: FastifyRequest,
|
||||
): Record<string, unknown> | undefined => {
|
||||
const input = path(['query', 'input'], request);
|
||||
try {
|
||||
return typeof input === 'string' ? JSON.parse(input).json : input;
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export function requestLoggingHook(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
done: HookHandlerDoneFunction,
|
||||
) {
|
||||
if (ignoreMethods.includes(request.method)) {
|
||||
return done();
|
||||
}
|
||||
if (ignoreLog.some((path) => request.url.startsWith(path))) {
|
||||
return done();
|
||||
}
|
||||
if (request.url.includes('trpc')) {
|
||||
request.log.info('request done', {
|
||||
url: request.url.split('?')[0],
|
||||
method: request.method,
|
||||
input: getTrpcInput(request),
|
||||
elapsed: reply.elapsedTime,
|
||||
});
|
||||
} else {
|
||||
request.log.info('request done', {
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
elapsed: reply.elapsedTime,
|
||||
headers: pick(
|
||||
[
|
||||
'openpanel-client-id',
|
||||
'openpanel-sdk-name',
|
||||
'openpanel-sdk-version',
|
||||
'user-agent',
|
||||
],
|
||||
request.headers,
|
||||
),
|
||||
body: request.body,
|
||||
});
|
||||
}
|
||||
done();
|
||||
}
|
||||
14
apps/api/src/hooks/timestamp.hook.ts
Normal file
14
apps/api/src/hooks/timestamp.hook.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import type {
|
||||
FastifyReply,
|
||||
FastifyRequest,
|
||||
HookHandlerDoneFunction,
|
||||
} from 'fastify';
|
||||
|
||||
export function timestampHook(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
done: HookHandlerDoneFunction,
|
||||
) {
|
||||
request.timestamp = Date.now();
|
||||
done();
|
||||
}
|
||||
Reference in New Issue
Block a user