Next.js Discord

Discord Forum

Creating a Prisma ApiHandler crashing.

Unanswered
JimJam posted this in #help-forum
Open in Discord
I'm wondering if anyone can help me here. I'm using prisma in app/api/model/route.ts and trying to create a common handler than can be used across all routes. i.e. a function that takes a prisma model and returns the required actions, for example:

import { PrismaClient } from "@prisma/client";
import { NextRequest, NextResponse } from "next/server";
import { parseQuery } from "~/utils/parse-query";

type PrismaModel = InstanceType<typeof PrismaClient>;
type ApiFunction = (request: NextRequest) => Promise<NextResponse>;

export function apiHandler(prismaModel: PrismaModel, defaultLimit = 10) {
  console.log("apiHandler", prismaModel);
  const getItems: ApiFunction = async (request) => {
    const rawArgs = request.nextUrl.searchParams.toString();
    const args = parseQuery(rawArgs);
    const page = Number(args.skip) || 0;
    const limit = Number(args.take) || defaultLimit;

    console.log("PrismaModel", prismaModel);

    try {
      const [total, items] = await prismaModel.$transaction([
        prismaModel.count({ where: args.where }),
        prismaModel.findMany({ ...args, skip: page, take: limit })
      ]);

      const pagination = {
        total: total,
        page: page + 1,
        limit: limit
      };

      return NextResponse.json({ data: items, pagination }, { status: 200 });
    } catch (e) {
      return NextResponse.json(
        {
          error: {
            name: "Error",
            message: "Could not fetch items",
            key: "ERROR_COULD_NOT_FETCH"
          }
        },
        { status: 500 }
      );
    }
  };

  const postItem: ApiFunction = async (request) => {
    const body = await request.json();
    try {
      const item = await prismaModel.create({ data: body });
      return NextResponse.json({ data: item }, { status: 201 });
    } catch (e) {
      return NextResponse.json(
        {
          error: {
            name: "Error",
            message: "Could not create item",
            key: "ERROR_COULD_NOT_CREATE"
          }
        },
        { status: 500 }
      );
    }
  };

  const updateItem: ApiFunction = async (request) => {
    const body = await request.json();
    try {
      const item = await prismaModel.update({
        where: { id: body.id },
        data: body
      });
      return NextResponse.json({ data: item }, { status: 200 });
    } catch (e) {
      return NextResponse.json(
        {
          error: {
            name: "Error",
            message: "Could not update item",
            key: "ERROR_COULD_NOT_UPDATE"
          }
        },
        { status: 500 }
      );
    }
  };

  const deleteItem: ApiFunction = async (request) => {
    const body = await request.json();
    try {
      await prismaModel.delete({
        where: { id: body.id }
      });
      return NextResponse.json({}, { status: 204 });
    } catch (e) {
      return NextResponse.json(
        {
          error: {
            name: "Error",
            message: "Could not delete item",
            key: "ERROR_COULD_NOT_DELETE"
          }
        },
        { status: 500 }
      );
    }
  };

  return { getItems, postItem, updateItem, deleteItem };
}

export type { ApiFunction };


Then using it in a route like so:

import { prisma } from "~/lib/prisma";
import { NextRequest, NextResponse } from "next/server";
import { apiHandler } from "~/utils/api-handler";

// export const runtime = 'edge'
const model = prisma.organisation;
const handlers = apiHandler(model as any);

export async function GET(request: NextRequest): Promise<NextResponse> {
  return await handlers.getItems(request);
}


But when i visit the route it hangs, i don't even reach the first console.log.

Does anyone have ideas how to achieve this?

0 Replies