2022-06-10 18:38:46 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
|
|
|
|
import { getServerErrorFromUnkown } from "./getServerErrorFromUnkown";
|
2022-06-14 15:32:37 +00:00
|
|
|
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);
|
2022-06-13 22:12:27 +00:00
|
|
|
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;
|