2022-03-29 01:59:57 +00:00
|
|
|
import { NextMiddleware } from "next-api-middleware";
|
|
|
|
|
2022-03-30 12:17:55 +00:00
|
|
|
export const httpMethod = (allowedHttpMethod: "GET" | "POST" | "PATCH" | "DELETE"): NextMiddleware => {
|
2022-03-29 01:59:57 +00:00
|
|
|
return async function (req, res, next) {
|
|
|
|
if (req.method === allowedHttpMethod || req.method == "OPTIONS") {
|
|
|
|
await next();
|
|
|
|
} else {
|
2022-03-30 12:17:55 +00:00
|
|
|
res.status(405).json({ message: `Only ${allowedHttpMethod} Method allowed` });
|
2022-03-29 01:59:57 +00:00
|
|
|
res.end();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
2022-04-07 01:29:53 +00:00
|
|
|
// Made this so we can support several HTTP Methods in one route and use it there.
|
|
|
|
// Could be further extracted into a third function or refactored into one.
|
|
|
|
// that checks if it's just a string or an array and apply the correct logic to both cases.
|
2022-04-03 22:49:05 +00:00
|
|
|
export const httpMethods = (allowedHttpMethod: string[]): NextMiddleware => {
|
|
|
|
return async function (req, res, next) {
|
|
|
|
if (allowedHttpMethod.map((method) => method === req.method)) {
|
|
|
|
await next();
|
|
|
|
} else {
|
|
|
|
res.status(405).json({ message: `Only ${allowedHttpMethod} Method allowed` });
|
|
|
|
res.end();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2022-03-30 12:17:55 +00:00
|
|
|
export const HTTP_POST = httpMethod("POST");
|
|
|
|
export const HTTP_GET = httpMethod("GET");
|
|
|
|
export const HTTP_PATCH = httpMethod("PATCH");
|
|
|
|
export const HTTP_DELETE = httpMethod("DELETE");
|
2022-04-03 22:49:05 +00:00
|
|
|
export const HTTP_GET_DELETE_PATCH = httpMethods(["GET", "DELETE", "PATCH"]);
|
2022-04-07 01:29:53 +00:00
|
|
|
export const HTTP_GET_OR_POST = httpMethods(["GET", "POST"]);
|