next-openapi-gen 0.0.8 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,16 +1,112 @@
1
- # Next OpenAPI Gen
1
+ # next-openapi-gen
2
2
 
3
- **Next OpenAPI Gen** is a library that automatically generates an `openapi.json` specification for your Next.js project. This tool scans your API routes, schemas, and models, and generates a complete OpenAPI definition.
3
+ **next-openapi-gen** super fast and easy way to generate OpenAPI 3.0 documentation automatically from API routes in a Next.js 14.
4
+
5
+ ## Prerequisites
6
+
7
+ - Nextjs >= 14
8
+ - Node >= 18
4
9
 
5
10
  ## Features
6
11
 
7
- - Auto-generates `next.openapi.json` in your project's root directory.
8
- - Scans API routes from `app/api/` and includes them in the generated OpenAPI specification.
9
- - Scans schemas from the `schemas/` directory and includes them in the OpenAPI components.
12
+ - **Automatic OpenAPI Generation**: Generate OpenAPI 3.0 documentation from your Next.js routes, automatically parsing TypeScript types for parameters, request bodies and responses.
13
+ - **TypeScript Type Scanning**: Automatically resolve TypeScript types for params, body, and responses based on your API endpoint's TypeScript definitions. Field comments in TypeScript types are reflected as descriptions in the OpenAPI schema.
14
+ - **JSDoc-Based Documentation**: Document API routes with JSDoc comments, including tags like `@openapi`, `@auth`, `@desc`, `@params`, `@body`, and `@response` to easily define route metadata.
15
+ - **UI Interface Options**: Choose between Swagger UI, Elements, or Redoc to visualize your API documentation. Customize the interface to fit your preferences.
16
+ - **Real-time Documentation**: As your API evolves, regenerate the OpenAPI documentation with a single command, ensuring your documentation is always up to date.
17
+ - **Easy configuration**: Customize generator behavior using the `next.openapi.json` configuration file, allowing for quick adjustments without modifying the code.
10
18
 
11
19
  ## Installation
12
20
 
13
- To install **Next OpenAPI Gen**, run:
21
+ ```bash
22
+ yarn add next-openapi-gen
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### Step 1: Initialize Configuration and Setup
28
+
29
+ Run the following command to generate the `next.openapi.json` configuration file and automatically set up Swagger UI with `/api-docs` routes:
30
+
31
+ ```bash
32
+ npx next-openapi-gen init
33
+ ```
34
+
35
+ This command does the following:
36
+
37
+ - Generates a `next.openapi.json` file, which stores the OpenAPI configuration for your project.
38
+ - Installs Swagger UI to provide an API documentation interface.
39
+ - Adds an `/api-docs` route in the Next.js app for visualizing the generated OpenAPI documentation.
40
+
41
+ ### Step 2: Add JSDoc Comments to Your API Routes
42
+
43
+ Annotate your API routes using JSDoc comments. Here's an example:
44
+
45
+ ```typescript
46
+ //app/api/auth/reset-password/route.ts
47
+
48
+ import { type NextRequest } from "next/server";
49
+
50
+ type ResetPasswordParams = {
51
+ token: string; // Token for resetting the password
52
+ };
53
+
54
+ type ResetPasswordBody = {
55
+ password: string; // The new password for the user
56
+ };
57
+
58
+ type ResetPasswordResponse = {
59
+ message: string; // Confirmation message that password has been reset
60
+ };
61
+
62
+ /**
63
+ * Reset the user's password.
64
+ * @auth: bearer
65
+ * @desc: Allows users to reset their password using a reset token.
66
+ * @params: ResetPasswordParams
67
+ * @body: ResetPasswordBody
68
+ * @response: ResetPasswordResponse
69
+ */
70
+ export async function POST(req: Request) {
71
+ const searchParams = req.nextUrl.searchParams;
72
+
73
+ const token = searchParams.get("token"); // Token from query params
74
+ const { password } = await req.json(); // New password from request body
75
+
76
+ // Logic to reset the user's password
77
+
78
+ return Response.json({ message: "Password has been reset" });
79
+ }
80
+ ```
81
+
82
+ - `@openapi`: Marks the route for inclusion in the OpenAPI specification.
83
+ - `@auth`: Specifies authentication type used for API route (`basic`, `bearer`, `apikey`)
84
+ - `@desc`: Provides a detailed description of the API route.
85
+ - `@params`: Specifies the TypeScript interface or Zod schema for the query parameters.
86
+ - `@body`: Specifies the TypeScript interface or Zod schema for the request body.
87
+ - `@response`: Specifies the TypeScript interface or Zod schema for the response.
88
+
89
+ ### Step 3: Generate the OpenAPI Specification
90
+
91
+ Run the following command to generate the OpenAPI schema based on your API routes:
14
92
 
15
93
  ```bash
16
- npm install next-openapi-gen --save-dev
94
+ npx next-openapi-gen generate
95
+ ```
96
+
97
+ This command processes all your API routes, extracts the necessary information from JSDoc comments, and generates the OpenAPI schema, typically saved to a `swagger.json` file in the `public` folder.
98
+
99
+ ### Step 4: View API Documentation
100
+
101
+ With the `/api-docs` route generated from the init command, you can now access your API documentation through Swagger UI by navigating to `http://localhost:3000/api-docs`.
102
+
103
+ ## Configuration Options
104
+
105
+ The `next.openapi.json` file allows you to configure the behavior of the OpenAPI generator, including options such as:
106
+
107
+ - **apiDir**: (default: `./src/app/api`) The directory where your API routes are stored.
108
+ - **schemaDir**: (default: `./src`) The directory where your schema definitions are stored.
109
+ - **docsUrl**: (default: `./api-docs`) Route where OpenAPI UI is available.
110
+ - **ui**: (default: `swagger`) OpenAPI UI interface.
111
+ - **outputFile**: (default: `./swagger.json`) The file where the generated OpenAPI specification will be saved in `public` folder.
112
+ - **includeOpenApiRoutes**: (default: `false`) When `true`, the generator will only include routes that have the `@openapi` tag in their JSDoc comments.
@@ -65,7 +65,7 @@ export class RouteProcessor {
65
65
  const routePath = this.getRoutePath(filePath);
66
66
  const rootPath = capitalize(routePath.split("/")[1]);
67
67
  const operationId = getOperationId(routePath, method);
68
- const { summary, description, isOpenApi } = dataTypes;
68
+ const { summary, description, auth, isOpenApi } = dataTypes;
69
69
  if (this.config.includeOpenApiRoutes && !isOpenApi) {
70
70
  // If flag is enabled and there is no @openapi tag, then skip path
71
71
  return;
@@ -79,8 +79,18 @@ export class RouteProcessor {
79
79
  summary: summary,
80
80
  description: description,
81
81
  tags: [rootPath],
82
- parameters: params,
83
82
  };
83
+ // Add auth
84
+ if (auth) {
85
+ definition.security = [
86
+ {
87
+ [auth]: [],
88
+ },
89
+ ];
90
+ }
91
+ if (params) {
92
+ definition.parameters = params;
93
+ }
84
94
  // Add request body
85
95
  if (MUTATION_HTTP_METHODS.includes(method.toUpperCase())) {
86
96
  definition.requestBody =
package/dist/lib/utils.js CHANGED
@@ -8,6 +8,7 @@ export function extractJSDocComments(path) {
8
8
  let paramsType = "";
9
9
  let bodyType = "";
10
10
  let responseType = "";
11
+ let auth = "";
11
12
  let isOpenApi = false;
12
13
  if (comments) {
13
14
  comments.forEach((comment) => {
@@ -17,6 +18,21 @@ export function extractJSDocComments(path) {
17
18
  const summaryIndex = isOpenApi ? 1 : 0;
18
19
  summary = commentValue.split("\n")[summaryIndex];
19
20
  }
21
+ if (commentValue.includes("@auth")) {
22
+ const regex = /@auth:\s*(.*)/;
23
+ const value = commentValue.match(regex)[1].trim();
24
+ switch (value) {
25
+ case "bearer":
26
+ auth = "BearerAuth";
27
+ break;
28
+ case "basic":
29
+ auth = "BasicAuth";
30
+ break;
31
+ case "apikey":
32
+ auth = "ApiKeyAuth";
33
+ break;
34
+ }
35
+ }
20
36
  if (commentValue.includes("@desc")) {
21
37
  const regex = /@desc:\s*(.*)/;
22
38
  description = commentValue.match(regex)[1].trim();
@@ -33,6 +49,7 @@ export function extractJSDocComments(path) {
33
49
  });
34
50
  }
35
51
  return {
52
+ auth,
36
53
  summary,
37
54
  description,
38
55
  paramsType,
@@ -11,6 +11,15 @@ export default {
11
11
  description: "Local development server",
12
12
  },
13
13
  ],
14
+ components: {
15
+ securitySchemes: {
16
+ BearerAuth: {
17
+ type: "http",
18
+ scheme: "bearer",
19
+ bearerFormat: "JWT",
20
+ },
21
+ },
22
+ },
14
23
  apiDir: "./src/app/api",
15
24
  schemaDir: "./src",
16
25
  docsUrl: "api-docs",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "next-openapi-gen",
3
- "version": "0.0.8",
4
- "description": "Automatically generate OpenAPI documentation for Next.js API",
3
+ "version": "0.0.10",
4
+ "description": "Super fast and easy way to generate OpenAPI 3.0 documentation automatically from API routes in a NextJS 14.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.mjs",