2022-06-10 18:38:46 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
|
2022-07-20 13:34:17 +00:00
|
|
|
import { getServerErrorFromUnknown } from "./getServerErrorFromUnknown";
|
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 */
|
2022-11-17 21:38:34 +00:00
|
|
|
export function defaultResponder<T>(f: Handle<T>) {
|
2022-06-10 18:38:46 +00:00
|
|
|
return async (req: NextApiRequest, res: NextApiResponse) => {
|
2022-06-28 00:38:01 +00:00
|
|
|
let ok = false;
|
2022-06-10 18:38:46 +00:00
|
|
|
try {
|
|
|
|
performance.mark("Start");
|
|
|
|
const result = await f(req, res);
|
2022-06-28 00:38:01 +00:00
|
|
|
ok = true;
|
2022-06-13 22:12:27 +00:00
|
|
|
if (result) res.json(result);
|
2022-06-10 18:38:46 +00:00
|
|
|
} catch (err) {
|
2022-08-26 00:48:50 +00:00
|
|
|
console.error(err);
|
2022-07-20 13:34:17 +00:00
|
|
|
const error = getServerErrorFromUnknown(err);
|
2022-06-10 18:38:46 +00:00
|
|
|
res.statusCode = error.statusCode;
|
|
|
|
res.json({ message: error.message });
|
|
|
|
} finally {
|
|
|
|
performance.mark("End");
|
2022-06-28 00:38:01 +00:00
|
|
|
performance.measure(`[${ok ? "OK" : "ERROR"}][$1] ${req.method} '${req.url}'`, "Start", "End");
|
2022-06-10 18:38:46 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|