Studying Prisma Pagination
Let's practicing Prisma ORM doing some pagination
Initial setup | Server setup | Search and pagination | Celebrate
Initial Setup
-
Install Node.js and some Database (SQLite will be used here)
-
yarn init -y && yarn add prisma @prisma/client typescript ts-node @types/node nodemon
-
touch tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"strict": true,
"lib": ["esnext"],
"esModuleInterop": true,
}
}
-
npx prisma init --datasource-provider sqlite
-
Connect Database
a. Install VSCode extension for Prisma for auto format
b. If no extension, can run
npx prisma format
-
Create Schema
model Product {
id Int @id @default(autoincrement())
name String @unique
description String?
@@map("product")
}
-
npx prisma migrate dev --name init
- create/run migration -
npx prisma studio
-
Add about 5 differente products to test later
Server setup
-
yarn add express @types/express
-
touch index.ts
import express from 'express'
const app = express()
app.use(express.json())
app.listen('2222')
Search and Pagination
- add get /search route
import express, { Request, Response } from 'express'
//...
app.get('/search', async(req: Request, res: Response) => {
})
//...
-
npx prisma generate
-
add the generated database client
import express, { Request, Response } from 'express'
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient({ log: ["error", "info", "query", "warn"]})
- add the search logic
app.get('/search', async(req: Request, res: Response) => {
const search = req.query.q || ''
const take = req.query.take || 10
const skip = req.query.skip || 0
try {
const result = await prisma.product.findMany({
where: {
name: {
contains: String(search)
}
},
take: Number(take),
skip: Number(skip),
})
return res.json(result)
} catch(error) {
console.log(error)
return res.send(500).json({error})
}
})
- add dev script to package.json
"scripts": {
"dev": "nodemon index.ts"
},
-
run dev server
yarn dev
-
open browser and test
http://localhost:2222/search/?q=a&take=2&skip=2
Celebrate
🎉 Well done!