link-stack/fix/metamigo-common/plugins/request-id.ts
2023-03-07 14:09:49 +00:00

37 lines
829 B
TypeScript

import { Server } from "@hapi/hapi";
import { v4 as uuid } from "uuid";
interface RequestIdOptions {
header?: string;
}
const register = async (
server: Server,
options?: RequestIdOptions
): Promise<void> => {
const header = options?.header || "x-request-id";
server.ext("onPreResponse", async (request, h) => {
if (!request.response) {
return h.continue;
}
if ("isBoom" in request.response) {
const id = request.response.output.headers[header] || uuid();
request.response.output.headers[header] = id;
} else {
const id = request.headers[header] || uuid();
// @ts-ignore
request.response.header(header, id);
}
return h.continue;
});
};
const RequestIdPlugin = {
register,
name: "request-id",
version: "0.0.1",
};
export default RequestIdPlugin;