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

27 lines
878 B
TypeScript
Raw Normal View History

2022-06-10 18:38:46 +00:00
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerErrorFromUnkown } from "./getServerErrorFromUnkown";
import { performance } from "./perfObserver";
2022-06-10 18:38:46 +00:00
type Handle<T> = (req: NextApiRequest, res: NextApiResponse) => Promise<T>;
/** 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;