Overview

Query is a helper function that allows you to query the data from the database through API route. It supports pagination, filtering, and sorting.

URL Parameters

Here's an example of a URL with query parameters that you can use:

code

/api/users?_skip=0&_take=20&_sort=name:asc&status=active

Reserved parameters:

  • _skip: Skip the first N items (default: 0)
  • _take: Take the first N items (default: 20)
  • _sort: Sort items by a column in asc or desc order (e.g., name:asc)

Other query parameters are used to filter data. These are flattened objects that you can pass to filtering conditions for Prisma. Here's a URL with an advanced filtering example:

code

/api/users?OR.0.email.contains=john&OR.1.name.contains=john&OR.1.name.mode=insensitive

It will be parsed into:

json

{ "OR": [ { "email": { "contains": "john" } }, { "name": { "contains": "john", "mode": "insensitive" } } ] }

How to Use

You need to wrap it with the Prisma client's findMany method in an API route. Here's an example of how to use it:

ts

import { db } from '@/lib/server/db' import { Query } from '@/lib/server/query' import { type NextRequest, NextResponse } from 'next/server' export const GET = async (req: NextRequest) => { const data = await db.user.findMany( Query<typeof db.user>(req) ) return NextResponse.json(data) }

Also, you can append it with the fixed where condition or with other findMany arguments:

ts

const data = await db.user.findMany({ ...Query<typeof db.user>(req, { email: { endsWith: '@nextready.dev', }, // ...other fixed conditions }), include: { role: true } // ...other arguments })

References