### App Router API Route Setup Source: https://next-crud.js.org/index Sets up the next-crud handler for Next.js App Router API routes. This example demonstrates using the PrismaAdapter with a pre-configured prisma instance. ```typescript // app/api/[...nextcrud]/route.ts 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 } ``` -------------------------------- ### Installation Source: https://next-crud.js.org/index Installs the next-crud library using either Yarn or npm. Ensure you are using Prisma v5 or above for version 3 of the library; otherwise, use version 2 for Prisma v4 or older. ```bash yarn add @premieroctet/next-crud npm install -S @premieroctet/next-crud ``` -------------------------------- ### Prisma Schema Example Source: https://next-crud.js.org/index An example Prisma schema defining a 'User' model, which can be used with next-crud to automatically generate API routes for user management. ```prisma model User { id Int @id @default(autoincrement()) name String? email String? } ``` -------------------------------- ### API Pagination Example Source: https://next-crud.js.org/pagination Demonstrates how to request a specific page of data using the `page` query parameter in an API request. This is the primary method for client-side pagination. ```http /api/users?page=10 ``` -------------------------------- ### Page Router API Route Setup Source: https://next-crud.js.org/index Configures the next-crud handler for Next.js Page Router API routes. It requires an adapter, such as PrismaAdapter, which needs an initialized PrismaClient instance. ```typescript // pages/api/[...nextcrud].ts import NextCrud, { PrismaAdapter } from '@premieroctet/next-crud' import { 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 ``` -------------------------------- ### API Cursor Parameter Source: https://next-crud.js.org/api-docs/adapters The 'cursor' parameter is a JSON object used to specify the starting point or offset for database queries. It contains a single key-value pair, where the key and value correspond to an entry in the database, defining the beginning of the result set. ```APIDOC API Endpoint Query Parameters: cursor: type: JSON object description: A JSON object containing only 1 key and a matching value corresponding to an entry in the database which is the starting point of the result of the query. You can see that as an offset. example: "/api/users?cursor={\"id\":1}" ``` -------------------------------- ### Next Crud PrismaAdapter Options Source: https://next-crud.js.org/api-docs/adapters Configuration options for the PrismaAdapter, allowing customization of supported models, primary key identification, and Prisma client instance. ```javascript PrismaAdapter constructor options: models: Optional array of Prisma model names to support. Defaults to all models in the Prisma client. primaryKey: The name of the field used as the unique identifier for resources. Defaults to 'id'. prismaClient: An instance of your Prisma client, required for the adapter to interact with the database. manyRelations: An object mapping model names to arrays of their relations (including nested ones) that can be queried via the 'where' filter. Example: { User: ['posts', 'posts.author'] }. ``` -------------------------------- ### NextCrud Function Configuration Options Source: https://next-crud.js.org/api-docs/options Details the configuration object accepted by the NextCrud function. This includes defining models, specifying adapters, setting default exposure strategies, and configuring callbacks and resource ID formatting. ```APIDOC NextCrud Function Options: The `NextCrud` function accepts a single argument: an object with the following keys. #### models An object where each key corresponds to a model passed to your adapter. It defines specific configurations for each model. ```typescript type TModelOption = { name?: string only?: RouteType[] // An array of routes to serve, by default it serves all possible routes exclude?: RouteType[] // An array of routes to exclude from being served, by default no route is excluded formatResourceId?: (resourceId: string) => string | number } type TModelsOptions = { [key in M]?: TModelOption } ``` * `name`: Optional string to specify a custom name for the model's routes. * `only`: Optional array of `RouteType` values to specify which routes should be exposed for this model. * `exclude`: Optional array of `RouteType` values to specify which routes should be excluded for this model. * `formatResourceId`: Optional function to format the resource ID for routes involving a single resource. **Example Usage:** ```javascript NextCrud({ adapter: new PrismaAdapter({ prismaClient: myPrismaClient, }), models: { [Prisma.ModelName.User]: { name: 'users', only: [RouteType.READ_ALL], }, }, defaultExposeStrategy: 'all', }) ``` **Available `RouteType` values:** * `CREATE` * `READ_ONE` * `READ_ALL` * `UPDATE` * `DELETE` *TypeScript users can import `RouteType` from `@premieroctet/next-crud`.* #### adapter A required instance of an adapter class. This connects NextCrud to your data source (e.g., Prisma, TypeORM). #### defaultExposeStrategy Determines the default exposure of routes. Options are `'all'` (exposes all routes by default) or `'none'` (exposes only routes specified in `only`). Defaults to `'all'`. #### formatResourceId An optional function to customize how resource IDs are formatted when retrieving single resources. By default, it converts numeric strings to numbers; otherwise, it keeps them as strings. #### onRequest An optional callback function executed before a request is processed. See [this section](/api-docs/callbacks) for details. #### onSuccess An optional callback function executed after a request is successfully processed. See [this section](/api-docs/callbacks) for details. #### onError An optional callback function executed when an error occurs during request processing. See [this section](/api-docs/callbacks) for details. #### middlewares An optional array of middleware functions to be applied to the CRUD routes. See [this section](/api-docs/middlewares) for details. #### pagination Configuration for pagination. Accepts an object with the following shape: ```typescript interface IPaginationConfig { perPage: number // default number of elements to display on each page } ``` ``` -------------------------------- ### Generated API Routes Source: https://next-crud.js.org/index Lists the standard CRUD API endpoints automatically created by next-crud for a given resource, such as 'users', based on a Prisma model. ```APIDOC Resource: users (based on Prisma User model) | Method | Endpoint | Description | |---------|-------------------|--------------------------| | GET | `/api/users` | Get all users | | GET | `/api/users/[id]` | Get one user by ID | | POST | `/api/users` | Create one user | | PUT | `/api/users/[id]` | Update one user by ID | | PATCH | `/api/users/[id]` | Partially update user by ID | | DELETE | `/api/users/[id]` | Delete one user by ID | Additional query parameters can be used for filtering and pagination on GET requests. ``` -------------------------------- ### Next Crud Query Parameters Source: https://next-crud.js.org/api-docs/adapters Details the structure and purpose of various query parameters used for filtering, sorting, and limiting data retrieval within Next Crud adapters. ```javascript select: An object with boolean values or nested objects for nested fields, e.g., { user: true, articles: { user: true } }. includes: Same as select, used for including related data. where: An object obtained by applying JSON.parse on the associated query param, used for filtering. orderBy: An object obtained by applying JSON.parse on the associated query param, used for sorting. limit: A number specifying the maximum number of records to return. skip: A number specifying the number of records to skip for pagination. distinct: A string specifying a field to return distinct values for. ``` -------------------------------- ### Next Crud IAdapter Interface Source: https://next-crud.js.org/api-docs/adapters Defines the contract for custom database adapters in Next Crud. It specifies methods for querying, creating, updating, and deleting data, along with handling pagination and model introspection. ```typescript export interface IAdapter< T, Q = IParsedQueryParams, M extends string = string > { models: M[] init?: () => Promise // Called before creating the handler in case you need to initialize the adapter with asynchronous code parseQuery(resourceName: M, query?: IParsedQueryParams): Q getAll(resourceName: M, query?: Q): Promise // GET /api/resourceName getPaginationData(resourceName: M, query: Q): Promise // Used for pagination getOne(resourceName: M, resourceId: string | number, query?: Q): Promise // GET /api/resourceName/:id create(resourceName: M, data: any, query?: Q): Promise // POST /api/resourceName update( resourceName: M, resourceId: string | number, data: any, query?: Q ): Promise // PUT/PATCH /api/resourceName/:id delete(resourceName: M, resourceId: string | number, query?: Q): Promise // DELETE /api/resourceName/:id connect?: () => Promise // connect function to your DB disconnect?: () => Promise // disconnect function to your DB handleError?: (err: Error) => void // Used to throw a custom error of your own getModels(): M[] getModelsJsonSchema?: () => any // JSON Schema of your models, used for Swagger mapModelsToRouteNames?: () => { [key in M]?: string } // Object associating the model name with a route name } ``` -------------------------------- ### Page Size Configuration Source: https://next-crud.js.org/pagination Explains how to control the number of items per page. This can be set via the `limit` query parameter in the URL or through the NextCrud configuration options. ```http /api/users?page=1&limit=10 ``` -------------------------------- ### Next Crud Swagger Configuration Types Source: https://next-crud.js.org/swagger Defines the TypeScript types used to configure Swagger integration within the Next Crud library. These types specify how to set up the Swagger UI, including titles, paths, API URLs, and detailed operation configurations for different API routes. ```typescript export type TSwaggerType = { name: string isArray?: boolean description?: string required?: boolean } export type TSwaggerOperation = { summary?: string responses?: Record body?: TSwaggerType response: TSwaggerType } export type TSwaggerTag = { name?: string description?: string externalDocs?: { description: string url: string } } export type TSwaggerParameter = { name: string description?: string schema: { type: string } & any } export type TSwaggerModelsConfig = { [key in M]?: { tag: TSwaggerTag type?: TSwaggerType routeTypes?: { [RouteType.READ_ALL]?: TSwaggerOperation [RouteType.READ_ONE]?: TSwaggerOperation [RouteType.CREATE]?: TSwaggerOperation [RouteType.UPDATE]?: TSwaggerOperation [RouteType.DELETE]?: TSwaggerOperation } additionalQueryParams?: TSwaggerParameter[] } } export type TSwaggerConfig = { title?: string // Title of the Swagger enabled?: boolean path?: string // Path to the docs apiUrl: string // URL that points to the API root, eg: http://localhost:3000/api config?: TSwaggerModelsConfig } ``` -------------------------------- ### Adapter Pagination Method Source: https://next-crud.js.org/pagination Defines the `getPaginationData` method required for custom adapters to support pagination. It takes a query object and must return pagination metadata. ```typescript getPaginationData(query: Q): Promise ``` -------------------------------- ### API: skip Query Parameter Source: https://next-crud.js.org/query-params Specify the number of elements to skip from the beginning of the dataset, useful for pagination. ```APIDOC skip: Description: The number of elements to skip the first n elements from the query. Example: /api/users?skip=2 ``` -------------------------------- ### API Callbacks Source: https://next-crud.js.org/api-docs/callbacks Callbacks are functions executed at specific points in the request lifecycle to allow custom logic. This includes handling requests before database operations, after successful operations, and during error conditions. ```APIDOC onRequest: Description: A request has arrived and the callback is executed right before any action on the database. Arguments: - request: The incoming request object. - routeInfo: An object containing the route type, the resource id and the resource name. Usage: - Add custom content to query parameters. - Perform debugging. onSuccess: Description: The request is successful and the callback is executed right before ending the handler. Arguments: - request: The request object. Usage: - Perform post-success actions. onError: Description: The request is unsuccessful and the callback is executed on the first error it meets. Arguments: - request: The request object. - error: The thrown error object. Usage: - Notify error monitoring systems (e.g., Bugsnag). ``` -------------------------------- ### API: select Query Parameter Source: https://next-crud.js.org/query-params Specify which fields to retrieve from the model. Supports selecting nested fields by separating them with a dot (.). ```APIDOC select: Description: A list of fields which will be retrieved to the model. You can select nested fields by just separating the fields with a ".". Example: /api/users?select=id,username,articles,articles.id Response Shape Example: { id: 'something', username: 'something', articles: [ { id: 'something' } ] } ``` -------------------------------- ### API: include Query Parameter Source: https://next-crud.js.org/query-params Specify related model relations to include in the response. Supports nested relations similar to the 'select' parameter. ```APIDOC include: Description: A list of fields which corresponds to the model relations to include. You can also include nested fields just like you would do with `select`. Example: /api/users?include=articles Note: With Prisma, make sure you don't use `include` in combination with `select` or the request will fail. ``` -------------------------------- ### API: where Query Parameter Source: https://next-crud.js.org/query-params Define search conditions using a JSON object, supporting various operators for filtering data. Heavily inspired by nest-crud. ```APIDOC where: Description: A JSON representation of the search conditions. Supports the following operators: - $eq (=, equal) - $neq (!=, not equal) - $in (IN, in range, must be an array) - $notin (NOT IN, not in range, must be an array) - $lt (<, lower than, must be a numeric value) - $lte (<=, lower than or equal, must be a numeric value) - $gt (>, greater than, must be a numeric value) - $gte (>=, greater than or equal, must be a numeric value) - $cont (LIKE %val%, contains string value) - $starts (LIKE val%, field starts with value) - $ends (LIKE %val, field ends with value) - $isnull (IS NULL, must be used in a string, e.g: "myfield": "$isnull") Logical Operators: - $and (AND): Should be an object, same as providing a JSON object directly. - $or (OR): Should be an object, applies an OR condition between each property. - $not (NOT): Should be an object, matches data that does not meet the criteria. Example: /api/users?where={"email":{"$and":{"$starts":"john", "$ends":".com"}}} ``` -------------------------------- ### Next Crud Middlewares API Source: https://next-crud.js.org/api-docs/middlewares Middlewares in Next Crud are functions executed after data retrieval from the database. They receive a context object containing the request and the retrieved data, along with a `next` function to proceed. Middlewares can mutate the context directly to modify the data before it is returned. ```APIDOC Middlewares API Middlewares are executed right after your data has been retrieved from the database. They are functions that accept the following arguments: 1. context: An object with the following shape: export type TMiddlewareContext = { req: TInternalRequest result: T | T[] // the data retrieved from the database } 2. next: A function to execute the next middleware in the stack. Usage Example: middlewares: [ (ctx, next) => { ctx.result = { myCustomKey: ctx.result, } next() }, ] Note: You need to mutate directly the context object. The following won't work: middlewares: [ ({ result }, next) => { result = { myCustomKey: result, } next() }, ] ``` -------------------------------- ### Pagination Data Structure Source: https://next-crud.js.org/pagination Specifies the expected shape of the pagination data returned by the adapter. It includes total item count, total page count, and the current page number. ```typescript type TPaginationDataPageBased = { total: number // total number of elements in the dataset, independent of pages pageCount: number // number of pages page: number // current page } type TPaginationData = TPaginationDataPageBased ``` -------------------------------- ### API: limit Query Parameter Source: https://next-crud.js.org/query-params Control the maximum number of elements to return in the query result. ```APIDOC limit: Description: A number representing the number of elements to return. Example: /api/users?limit=2 ``` -------------------------------- ### API: distinct Query Parameter Source: https://next-crud.js.org/query-params Remove duplicate entries from the dataset based on a specified field. ```APIDOC distinct: Description: A field name on which the duplicates are removed from the dataset. Example: /api/users?distinct=name ``` -------------------------------- ### API: orderBy Query Parameter Source: https://next-crud.js.org/query-params Specify the field and direction for sorting results. Supports ascending ($asc) and descending ($desc) order. ```APIDOC orderBy: Description: A JSON representation of the field to order by and its direction. Should be an object containing only 1 key (name of the field to order by) with a valid order operator. Operators: - $asc: for ascending order - $desc: for descending order Example: /api/users?orderBy={"name":"$asc"} ``` -------------------------------- ### Paginated Result Structure Source: https://next-crud.js.org/pagination Describes the structure of the API response when requesting paginated data. It includes the array of data items for the current page and the pagination metadata. ```typescript type TPaginationResult = { data: T[] // Page dataset pagination: TPaginationData } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.