Next Crud
next-crud
is a helper library that creates CRUD API routes with one simple function based on a Prisma model for Next.js.
Starting from version 3 of the lib, we only support Prisma v5 and above. Please install version 2 of the lib if you are using Prisma v4 or older.
Installation
yarn add @premieroctet/next-crud
npm install -S @premieroctet/next-crud
Quick Start
Page Router
// 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: prismaClient,
}),
})
return nextCrudHandler(req, res)
}
export default handler
App Router
// app/api/[...nextcrud]/route.ts
import { User, Post, Prisma } from '@prisma/client'
import NextCrud, { PrismaAdapter } from '@premieroctet/next-crud'
import { prisma } from '../../../../db'
const handler = async (req: Request) => {
const nextCrudHandler = await NextCrud({
adapter: new PrismaAdapter({
prismaClient: prisma,
}),
})
return nextCrudHandler(req)
}
export { handler as POST, handler as GET, handler as PUT, handler as DELETE }
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:
Endpoint | Description | |
---|---|---|
List | GET /api/users | Get all the users |
Get | GET /api/users/[id] | Get one user |
Add | POST /api/users | Create one user |
Edit | PUT /api/users/[id] | Update one user |
Partial edit | PATCH /api/users/[id] | Update one user (partial) |
Delete | DELETE/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.