Skip to content

Instantly share code, notes, and snippets.

@johnpolacek
Created April 21, 2023 20:30
Show Gist options
  • Save johnpolacek/4fa279254d8ca0d9f0e7a5086ea45dff to your computer and use it in GitHub Desktop.
Save johnpolacek/4fa279254d8ca0d9f0e7a5086ea45dff to your computer and use it in GitHub Desktop.
import { NextApiRequest, NextApiResponse } from "next";
export async function handleApiRequest(
req: NextApiRequest,
res: NextApiResponse,
expectedReqMethod: string,
handleRequest: (body: any) => Promise<any>
): Promise<void> {
if (req.method === expectedReqMethod) {
try {
const responseData = await handleRequest(req.body);
res.status(200).json(responseData);
} catch (error: unknown) {
handleErrorResponse(res, error);
}
} else {
res.status(405).json({ error: "Method not allowed" });
}
}
export function handleErrorResponse(
res: NextApiResponse,
error: unknown
): void {
if (error instanceof Error) {
res.status(500).json({ error: error.message });
} else {
res.status(500).json({ error: "An unknown error occurred" });
}
}
@johnpolacek
Copy link
Author

johnpolacek commented Apr 21, 2023

Example usage for handling both GET and POST requests:

// pages/api/messages.ts
import { NextApiRequest, NextApiResponse } from "next";
import { handleApiRequest } from "@/utils/api-utils";

const messages: string[] = [];

async function handleGetMessages() {
  return { messages };
}

async function handleCreateMessage(body: any) {
  const { message } = body;

  if (!message || typeof message !== "string") {
    throw new Error("Invalid message");
  }

  messages.push(message);
  return { success: true };
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "GET") {
    await handleApiRequest(req, res, "GET", handleGetMessages);
  } else if (req.method === "POST") {
    await handleApiRequest(req, res, "POST", handleCreateMessage);
  } else {
    res.status(405).json({ error: "Method not allowed" });
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment