Next Crud

NPM
  Version

NPM
  License

Github
  Actions

next-crud is a helper library that creates CRUD API routes with one simple function based on a Prisma model for Next.js.

Installation

yarn add @premieroctet/next-crud

npm install -S @premieroctet/next-crud

Quick Start

// pages/api/[...nextcrud.ts]
import NextCrud, { PrismaAdapter } from '@premieroctet/next-crud'
import { Prisma, PrismaClient } from '@prisma/client'
const prismaClient = new PrismaClient()
const handler = async (req, res) => {
const nextCrudHandler = await NextCrud({
adapter: new PrismaAdapter({
prismaClient: myPrismaClientInstance,
}),
})
return nextCrudHandler(req, res)
}
export default handler

Usage

Here is an example to create CRUD routes for an User resource given the following Prisma schema:

model User {
id Int @id @default(autoincrement())
name String?
email String?
}
  • Create a file under pages/api called [...nextcrud].ts.

  • Import the handler and the adapter you want to use, in that case we will use the prisma adapter but you can use your own one (see this section)

import NextCrud, { PrismaAdapter } from '@premieroctet/next-crud'
  • Then create the handler and export it
// pages/api/[...nextcrud.ts]
const handler = async (req, res) => {
const nextCrudHandler = await NextCrud({
adapter: new PrismaAdapter({
prismaClient: myPrismaClientInstance,
}),
})
return nextCrudHandler(req, res)
}
export default handler

More info about all the available options here

You can also find a working example on GitHub or you can run it on Codesandbox.

That will create the following routes:

EndpointDescription
ListGET /api/usersGet all the users
GetGET /api/users/[id]Get one user
AddPOST /api/usersCreate one user
EditPUT /api/users/[id]Update one user
Partial editPATCH /api/users/[id]Update one user (partial)
DeleteDELETE/api/users/[id]Delete one user

You can add multiple query parameters in the URL to make your request more precise, especially for requests where you get data.

You can then try a simple request using a tool like Postman, Insomnia or just your web browser on one of those routes.