2022-06-10 15:38:46 -03:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
|
2022-07-20 10:34:17 -03:00
|
|
|
import { getServerErrorFromUnknown } from "./getServerErrorFromUnknown";
|
2022-06-14 12:32:37 -03:00
|
|
|
import { performance } from "./perfObserver";
|
2022-06-10 15:38:46 -03:00
|
|
|
|
|
|
|
type Handle<T> = (req: NextApiRequest, res: NextApiResponse) => Promise<T>;
|
|
|
|
|
|
|
|
/** Allows us to get type inference from API handler responses */
|
2022-11-17 18:38:34 -03:00
|
|
|
export function defaultResponder<T>(f: Handle<T>) {
|
2022-06-10 15:38:46 -03:00
|
|
|
return async (req: NextApiRequest, res: NextApiResponse) => {
|
2022-06-27 21:38:01 -03:00
|
|
|
let ok = false;
|
2022-06-10 15:38:46 -03:00
|
|
|
try {
|
|
|
|
performance.mark("Start");
|
|
|
|
const result = await f(req, res);
|
2022-06-27 21:38:01 -03:00
|
|
|
ok = true;
|
2023-11-02 09:22:16 -03:00
|
|
|
if (result && !res.writableEnded) {
|
2023-11-16 05:48:46 -03:00
|
|
|
return res.json(result);
|
2023-11-02 09:22:16 -03:00
|
|
|
}
|
2022-06-10 15:38:46 -03:00
|
|
|
} catch (err) {
|
2022-08-25 21:48:50 -03:00
|
|
|
console.error(err);
|
2022-07-20 10:34:17 -03:00
|
|
|
const error = getServerErrorFromUnknown(err);
|
2023-11-16 05:48:46 -03:00
|
|
|
return res
|
|
|
|
.status(error.statusCode)
|
|
|
|
.json({ message: error.message, url: error.url, method: error.method });
|
2022-06-10 15:38:46 -03:00
|
|
|
} finally {
|
|
|
|
performance.mark("End");
|
2022-06-27 21:38:01 -03:00
|
|
|
performance.measure(`[${ok ? "OK" : "ERROR"}][$1] ${req.method} '${req.url}'`, "Start", "End");
|
2022-06-10 15:38:46 -03:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|