cal.pub0.org/packages/lib/server/defaultResponder.ts

30 lines
952 B
TypeScript
Raw Normal View History

2022-06-10 18:38:46 +00:00
import type { NextApiRequest, NextApiResponse } from "next";
import { performance } from "perf_hooks";
import { perfObserver } from ".";
import { getServerErrorFromUnkown } from "./getServerErrorFromUnkown";
type Handle<T> = (req: NextApiRequest, res: NextApiResponse) => Promise<T>;
2022-06-13 16:59:02 +00:00
perfObserver.observe({ type: "measure" });
2022-06-10 18:38:46 +00:00
/** Allows us to get type inference from API handler responses */
function defaultResponder<T>(f: Handle<T>) {
return async (req: NextApiRequest, res: NextApiResponse) => {
try {
performance.mark("Start");
const result = await f(req, res);
if (result) res.json(result);
2022-06-10 18:38:46 +00:00
} catch (err) {
const error = getServerErrorFromUnkown(err);
res.statusCode = error.statusCode;
res.json({ message: error.message });
} finally {
performance.mark("End");
performance.measure("Measuring endpoint: " + req.url, "Start", "End");
}
};
}
export default defaultResponder;