Giter Site home page Giter Site logo

summer-2014 / next-openapi-route-handler Goto Github PK

View Code? Open in Web Editor NEW

This project forked from omermecitoglu/next-openapi-route-handler

0.0 0.0 0.0 532 KB

a Next.js plugin to generate OpenAPI documentation from route handlers

License: MIT License

TypeScript 100.00%

next-openapi-route-handler's Introduction

Next OpenAPI Route Handler

npm version License: MIT

Overview

Next OpenAPI Route Handler is an open-source, lightweight, and easy-to-use Next.js plugin designed to build type-safe, self-documented APIs. It leverages TypeScript and Zod to create and validate route handlers, automatically generating OpenAPI documentation from your code. This package aims to simplify the process of building and documenting REST APIs with Next.js, ensuring your API endpoints are well-defined and compliant with OpenAPI specifications.

Key Features:

  • Type-Safe API Endpoints: Ensure your requests and responses are strongly typed with TypeScript.
  • Schema Validation: Use Zod schemas for object validation, automatically converted to JSON schema for OpenAPI.
  • Auto-Generated Documentation: Generate OpenAPI JSON specs from your route handlers.
  • Integration with Next.js: Works seamlessly with Next.js App Directory features.
  • Customizable: Compatible with existing Next.js projects and fully customizable to suit your needs.

Note: This package has a peer dependency on Next OpenAPI JSON Generator for extracting the generated OpenAPI JSON.

Requirements

To use @omer-x/next-openapi-route-handler, you'll need the following dependencies in your Next.js project:

Installation

To install this package, along with its peer dependency, run:

npm install @omer-x/next-openapi-route-handler @omer-x/next-openapi-json-generator

Usage

The createRoute function is used to define route handlers in a type-safe and self-documenting way. Below is a description of each property of the input parameter:

Property Type Description
operationId string Unique identifier for the operation.
method string HTTP method for the route (e.g., GET, POST, PUT, PATCH, DELETE).
summary string Short summary of the operation.
description string Detailed description of the operation.
tags string[] Tags for categorizing the operation.
pathParams ZodType (Optional) Zod schema for validating path parameters.
queryParams ZodType (Optional) Zod schema for validating query parameters.
requestBody ZodType Zod schema for the request body (required for POST, PUT, PATCH).
hasFormData boolean Is the request body a FormData
action (source: ActionSource) => Promise<Response> Function handling the request, receiving pathParams, queryParams, and requestBody.
responses Record<number, ResponseDefinition> Object defining possible responses, each with a description and optional content schema.

Action Source

Property Type Description
pathParams ZodType Parsed parameters from the request URL path.
queryParams ZodType Parsed parameters from the request query.
body ZodType Parsed request body.

Response Definition

Property Type Description
description string Description of the response.
content ZodType (Optional) Zod schema for the response body.
isArray boolean (Optional) Is the content an array?

Example

Here's an example of how to use createRoute to define route handlers:

import createRoute from "@omer-x/next-openapi-route-handler";
import z from "zod";

export const { GET } = createRoute({
  operationId: "getUser",
  method: "GET",
  summary: "Get a specific user by ID",
  description: "Retrieve details of a specific user by their ID",
  tags: ["Users"],
  pathParams: z.object({
    id: z.string().describe("ID of the user"),
  }),
  action: async ({ pathParams }) => {
    const results = await db.select().from(users).where(eq(users.id, pathParams.id));
    const user = results.shift();
    if (!user) return new Response(null, { status: 404 });
    return Response.json(user);
  },
  responses: {
    200: { description: "User details retrieved successfully", content: UserDTO },
    404: { description: "User not found" },
  },
});

This will generate an OpenAPI JSON like this:

{
  "openapi": "3.1.0",
  "info": {
    "title": "User Service",
    "version": "1.0.0"
  },
  "paths": {
    "/users": {
      "get": {
        ...
      },
      "post": {
        ...
      }
    },
    "/users/{id}": {
      "get": {
        "operationId": "getUser",
        "summary": "Get a specific user by ID",
        "description": "Retrieve details of a specific user by their ID",
        "tags": [
          "Users"
        ],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "required": true,
            "description": "ID of the user",
            "schema": {
              "type": "string",
              "description": "ID of the user"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "User details retrieved successfully",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UserDTO"
                }
              }
            }
          },
          "404": {
            "description": "User not found"
          }
        }
      },
      "patch": {
        ...
      },
      "delete": {
        ...
      }
    }
  },
  "components": {
    "schemas": {
      "UserDTO": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid",
            "description": "Unique identifier of the user"
          },
          "name": {
            "type": "string",
            "description": "Display name of the user"
          },
          "email": {
            "type": "string",
            "description": "Email address of the user"
          },
          "password": {
            "type": "string",
            "maxLength": 72,
            "description": "Encrypted password of the user"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time",
            "description": "Creation date of the user"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time",
            "description": "Modification date of the user"
          }
        },
        "required": [
          "id",
          "name",
          "email",
          "password",
          "createdAt",
          "updatedAt"
        ],
        "additionalProperties": false,
        "description": "Represents the data of a user in the system."
      },
      "NewUserDTO": {
        ...
      },
      "UserPatchDTO": {
        ...
      }
    }
  }
}

Important: This package cannot extract the OpenAPI JSON by itself. Use Next OpenAPI JSON Generator to extract the generated data as JSON.

An example can be found here

Screenshots

screenshot-1 screenshot-2 screenshot-3 screenshot-4
screenshot-5 screenshot-6 screenshot-7

License

This project is licensed under the MIT License. See the LICENSE file for details.

next-openapi-route-handler's People

Contributors

omermecitoglu avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.