### Copy DocsGeneratev6.ts Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/10-troubleshooting.md Use this command to copy the example command file for generating documentation. ```bash # From official repo cp DocsGeneratev6.ts.example commands/DocsGenerate.ts ``` -------------------------------- ### Provide Example Value Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/09-schema-discovery.md Use the `@example` decorator to provide a sample value for a field in the schema. ```typescript @column() // @example(john@example.com) public email: string ``` -------------------------------- ### @paramPath and @paramQuery Examples Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Examples for using @paramPath and @paramQuery decorators to define path and query parameters, including their descriptions, types, and required status. ```APIDOC ## @paramPath and @paramQuery Examples ### Description Examples for using `@paramPath` and `@paramQuery` decorators to define path and query parameters, including their descriptions, types, and required status. ### Usage - `@paramPath - Description - (@type(type) @required)` - `@paramQuery - Description - (@type(type) @required)` ### Examples - `@paramPath id - The ID of the source - @type(number) @required` - `@paramPath slug - The ID of the source - @type(string)` - `@paramQuery q - Search term - @type(string) @required` - `@paramQuery page - the Page number - @type(number)` ``` -------------------------------- ### Complete Product Listing Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/05-annotations-guide.md This example demonstrates a comprehensive set of annotations for a product listing endpoint, including summary, description, query parameters, sorting, response bodies, response headers, and tags. ```typescript export default class ProductsController { /** * @summary List all products * @description Returns paginated list of products with their categories and reviews. * Supports filtering by price range and category. * @paramQuery page - Current page - @type(number) * @paramQuery limit - Items per page - @type(number) * @paramQuery minPrice - Minimum price - @type(number) * @paramQuery maxPrice - Maximum price - @type(number) * @paramQuery categoryId - Filter by category - @type(number) * @paramUse(sorting) * @responseBody 200 - .with(category, reviews).paginated() - Success * @responseHeader 200 - X-Total-Count - Total products - @type(integer) * @responseBody 401 * @responseBody 422 - Invalid parameters * @tag products */ public async index({ request, response }: HttpContextContract) {} /** * @summary Get product by ID * @paramPath id - Product ID - @type(number) @required * @responseBody 200 - .with(category, reviews, reviews.author) * @responseBody 404 - Product not found * @tag products */ public async show({ params }: HttpContextContract) {} /** * @summary Create new product * @operationId createProduct * @requestBody * @responseBody 201 - - Created successfully * @responseBody 422 - Validation failed * @tag products */ public async store({ request, response }: HttpContextContract) {} /** * @summary Update product * @paramPath id - Product ID - @type(number) * @requestBody * @responseBody 200 - * @responseBody 404 - Not found * @responseBody 422 - Validation failed * @tag products */ public async update({ params, request }: HttpContextContract) {} /** * @summary Delete product * @paramPath id - Product ID - @type(number) * @responseBody 204 * @responseBody 404 - Not found * @tag products */ public async destroy({ params }: HttpContextContract) {} } ``` -------------------------------- ### Set Production Environment Variable Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/06-configuration-guide.md Example of how to set the `NODE_ENV` variable in your environment or `.env` file to indicate production mode. ```text NODE_ENV=production ``` -------------------------------- ### Provide Example Value for Model Property Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Use the `@example(value)` annotation to provide a specific example value for a model property. ```typescript // @example(johndoe@example.com) public email: string ``` -------------------------------- ### Generate Schema Example with Annotations Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Generates an example object for a given schema, allowing inclusion and exclusion of relations and fields. Use this to create detailed examples with specific data constraints. ```typescript getSchemaExampleBasedOnAnnotation( schema: string, inc?: string, // Relations to include exc?: string, // Fields to exclude onl?: string, // Fields to include only first?: string, parent?: string, deepRels?: string[] ): object ``` ```typescript const example = generator.getSchemaExampleBasedOnAnnotation( "User", "posts,profile", // Include these relations "password", // Exclude this field "" ) // Returns: { // id: 1, // name: "John Doe", // email: "john@example.com", // posts: [{ id: 1, title: "..." }, ...], // profile: { bio: "..." } // } ``` -------------------------------- ### Install Adonis AutoSwagger Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Install the package using pnpm. Other package managers can also be used. ```bash pnpm i adonis-autoswagger #using pnpm ``` -------------------------------- ### CommentParser getAnnotations Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/03-parsers-reference.md Example of how to use the `getAnnotations` method to fetch and log the summary of a controller action. ```typescript const annotations = await commentParser.getAnnotations( "app/controllers/products_controller.ts", "index" ) console.log(annotations.index.summary) // "Get a list of products" ``` -------------------------------- ### exampleByField() Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Generates an example value based on a field name, recognizing common patterns. ```APIDOC ## exampleByField() ### Description Generate example value based on field name. ### Signature ```typescript exampleByField(fieldName: string): any | null ``` ### Parameters - **fieldName** (string): Field name (snake_case or camelCase) **Returns:** Example value or null if no match **Recognized patterns:** | Field Name | Example | |------------|---------| | `email` or `email_address` | `user@example.com` | | `password` or `pwd` | `password123` | | `url` or `website` | `https://example.com` | | `slug` | `my-product` | | `phone` or `phone_number` | `+1234567890` | | `zip` or `postal_code` | `12345` | | `date` or `birth_date` | `2000-01-15` | ``` -------------------------------- ### Debug Log Output Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/06-configuration-guide.md An example of the console output when debug logging is enabled, illustrating discovered routes, schemas, and potential issues. ```text Route annotations: Checking if controllers have propper comment annotations ----- ✓ FOUND for index /api/products (GET /api/products) ✗ MISSING for show /api/products/:id (GET /api/products/:id) Found Schemas { Product, User, Category, ... } Using custom paths { '#models': 'app/models', ... } ``` -------------------------------- ### Generate Example Value by Validator Rule Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Generates an example string value based on a provided Vine validator rule name. Useful for creating mock data or schema examples. ```typescript exampleByValidatorRule(rule: string): string ``` -------------------------------- ### getSchemaExampleBasedOnAnnotation() Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Generates an example object for a given schema, allowing inclusion/exclusion of relations and fields. ```APIDOC ## getSchemaExampleBasedOnAnnotation() ### Description Generate example object for schema with annotations (relations, exclusions, etc.). ### Signature ```typescript getSchemaExampleBasedOnAnnotation( schema: string, inc?: string, // Relations to include exc?: string, // Fields to exclude onl?: string, // Fields to include only first?: string, parent?: string, deepRels?: string[] ): object ``` ### Parameters - **schema:** Schema name (Model, Interface, Validator) - **inc:** Comma-separated relation names to include - **exc:** Comma-separated field names to exclude - **onl:** Comma-separated field names to include only **Returns:** Example object conforming to schema **Example:** ```typescript const example = generator.getSchemaExampleBasedOnAnnotation( "User", "posts,profile", // Include these relations "password", // Exclude this field "" ) // Include all (except excluded) // Returns: { // id: 1, // name: "John Doe", // email: "john@example.com", // posts: [{ id: 1, title: "..." }, ...], // profile: { bio: "..." } // } ``` ``` -------------------------------- ### parseRef() Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Parses schema references with complex syntax to generate example data, optionally returning only the example value. ```APIDOC ## parseRef() ### Description Parse schema reference and generate example with complex syntax. ### Signature ```typescript parseRef(line: string, exampleOnly?: boolean): object | any ``` ### Parameters - **line** (string): Schema reference line (e.g., `.with(author)`) - **exampleOnly** (boolean): Return only example value, not full response **Returns:** OpenAPI response object or just the example **Schema reference syntax:** ```typescript // Single model // Array of models .with(rel1, rel2) // Include relations .exclude(field1) // Exclude fields .only(field1, field2) // Only these fields .paginated() // Wrap in pagination .append({json}) // Add properties .serialized(SerializerName) // Use serializer ``` ### Examples ```typescript // Single model with relations const ref1 = generator.parseRef(".with(posts, profile)") // Returns: { content: { "application/json": { schema: ..., example: {...} } } } // Array with exclusion const ref2 = generator.parseRef(".exclude(internalId)") // Paginated results const ref3 = generator.parseRef(".paginated()") // Returns pagination structure with data and meta // Just the example value const ref4 = generator.parseRef("", true) // Returns: { id: 1, name: "John", email: "john@example.com" } ``` ``` -------------------------------- ### Generate Docs Before Deploying Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/10-troubleshooting.md Ensure documentation is generated before starting the production server. Include the 'NODE_ENV=production node ace docs:generate' command in your build process. ```bash # ❌ Missing step npm run build npm start # ✅ Include docs generation npm run build NODE_ENV=production node ace docs:generate npm start ``` -------------------------------- ### Generate Example by Field Name Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Generates a sample value based on a field name, recognizing common patterns like 'email', 'password', or 'url'. This is useful for quick, type-appropriate example generation. ```typescript exampleByField(fieldName: string): any | null ``` -------------------------------- ### Convert JSON with Schema References to Examples Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Converts a JSON structure containing schema references into actual example values. Useful for generating complete JSON payloads with nested examples. ```typescript jsonToRef(json: any): object ``` ```typescript const json = { success: true, data: ".with(category)", count: 5 } const result = generator.jsonToRef(json) // Returns: { // success: true, // data: { id: 1, name: "...", category: { id: 1, name: "..." } }, // count: 5 // } ``` -------------------------------- ### exampleByType() Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Generates an example value based on a specified TypeScript or OpenAPI type. ```APIDOC ## exampleByType() ### Description Generate example value based on TypeScript/OpenAPI type. ### Signature ```typescript exampleByType(type: string): any ``` ### Parameters - **type** (string): Type name (string, number, boolean, date, etc.) **Returns:** Example value **Type mappings:** | Type | Example | |------|---------| | `string` | `"example text"` | | `number` | `1000` (random) | | `integer` | `1000` (random) | | `boolean` | `true` | | `date` | `"2024-01-15"` | | `datetime` | `"2024-01-15T10:30:00Z"` | | `email` | `"user@example.com"` | | `uuid` | `"550e8400-e29b-41d4-a716-446655440000"` | ``` -------------------------------- ### Generate Example by Type Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Generates a sample value based on a specified type, such as 'string', 'number', 'boolean', 'date', or 'uuid'. This function provides basic, type-correct examples. ```typescript exampleByType(type: string): any ``` -------------------------------- ### Production Build Script Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/08-complete-example.md A bash script demonstrating the production build process. It includes building the application, generating documentation using the custom Ace command, and copying the generated documentation files to the build output directory. ```bash #!/bin/bash # Build the application npm run build # Generate docs (in production environment) NODE_ENV=production node ace docs:generate # Copy generated docs to build output cp swagger.yml build/ cp swagger.json build/ ``` -------------------------------- ### Example AdonisJS User Model Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/09-schema-discovery.md A complete example of an AdonisJS User model with various decorators and type definitions. ```typescript // app/models/user.ts import { BaseModel, column, hasMany, computed } from "@adonisjs/lucid/orm" import { DateTime } from "luxon" import type { HasMany } from "@adonisjs/lucid/orm" import Post from "./post.js" export default class User extends BaseModel { @column({ isPrimary: true }) public id: number @column() // @required // @example(john@example.com) // @format(email) public email: string @column() // @required // @props({"minLength": 8}) public password: string @column() // @enum(user,admin,moderator) public role: string @column() // @example(John Doe) public name: string @column() // @format(uri) public avatar_url?: string @hasMany(() => Post) public posts: HasMany @column.dateTime({ autoCreate: true }) public created_at: DateTime @column.dateTime({ autoCreate: true, autoUpdate: true }) public updated_at: DateTime @computed() public get displayName() { return this.name || this.email } } ``` -------------------------------- ### Example Configuration Object Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/04-types-reference.md Demonstrates how to configure adonis-autoswagger using the `options` interface, including path, info, ignore patterns, common parameters/headers, and security schemes. ```typescript export default { path: path.dirname(url.fileURLToPath(import.meta.url)) + "/../", info: { title: "My API", version: "1.0.0", description: "API documentation" }, tagIndex: 2, snakeCase: true, debug: false, ignore: ["/swagger", "/docs"], common: { parameters: { pagination: [ { in: "query", name: "page", schema: { type: "number", example: 1 } }, { in: "query", name: "limit", schema: { type: "number", example: 20 } } ] }, headers: { paginated: { "X-Total": { description: "Total results", schema: { type: "integer", example: 100 } } } } }, securitySchemes: { ApiKeyAuth: { type: "apiKey", in: "header", name: "X-API-Key" } }, authMiddlewares: ["auth", "auth:api", "auth:jwt"], defaultSecurityScheme: "BearerAuth", persistAuthorization: true } as options ``` -------------------------------- ### GET /products/{id} Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Returns a specific product with its user relations. ```APIDOC ## GET /products/{id} ### Description Returns a product with it's relation on user and user relations. ### Method GET ### Endpoint /products/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Describe the path param #### Query Parameters - **foo** (string) - Required - Describe the query param ### Response #### Success Response (200) - **Product** (object) - Product with user and user relations #### Error Response (404) - Description: Product not found ``` -------------------------------- ### exampleByValidatorRule() Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Generates an example value based on a Vine validator rule. It supports specific rules like 'email' and provides a default string for others. ```APIDOC ## exampleByValidatorRule() ### Description Generate example value based on Vine validator rule. ### Signature ```typescript exampleByValidatorRule(rule: string): string ``` ### Parameters #### Path Parameters - `rule` (string) - Required - Vine rule name ### Returns Example value ### Recognized rules: | Rule | Example | |---------|------------------| | `email` | `user@example.com` | | Others | `"Some string"` | ``` -------------------------------- ### Annotation Syntax Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/05-annotations-guide.md Illustrates the general pattern for JSDoc annotations used for OpenAPI generation. Comments must be placed directly above the method definition. ```typescript /** * @directiveName [required-args] [- description] * @anotherDirective args */ public async methodName() {} ``` -------------------------------- ### @responseBody Examples Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Examples demonstrating the usage of the @responseBody decorator to specify response structures, including status codes, models, arrays, relations, and custom JSON. ```APIDOC ## @responseBody Examples ### Description Examples demonstrating the usage of the `@responseBody` decorator to specify response structures, including status codes, models, arrays, relations, and custom JSON. ### Usage - `@responseBody - Lorem ipsum Dolor sit amet` - `@responseBody // returns standard message` - `@responseBody - // returns model specification` - `@responseBody - // returns model-array specification` - `@responseBody - .with(relations, property1, property2.relations, property3.subproperty.relations) // returns a model and a defined relation` - `@responseBody - .with(relations).exclude(property1, property2, property3.subproperty) // returns model specification` - `@responseBody - .append("some":"valid json") // append additional properties to a Model` - `@responseBody - .paginated() // helper function to return adonisJS conform structure like {"data": [], "meta": {}}` - `@responseBody - .paginated(dataName, metaName) // returns a paginated model with custom keys for the data array and meta object, use `.paginated(dataName)` or `.paginated(,metaName)` if you want to override only one. Don't forget the ',' for the second parameter.` - `@responseBody - .only(property1, property2) // pick only specific properties` - `@responseBody - {"foo": "bar", "baz": ""} //returns custom json object and also parses the model` - `@responseBody - ["foo", "bar"] //returns custom json array` ``` -------------------------------- ### Example TypeScript Interfaces for Schema Generation Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/09-schema-discovery.md Provides example TypeScript interface definitions for pagination and user profiles that can be parsed into OpenAPI schemas. ```typescript // app/interfaces/pagination.ts export interface PaginatedResponse { data: T[] meta: { total: number per_page: number current_page: number } } // app/interfaces/user_profile.ts export interface UserProfile { id: number email: string name: string bio?: string avatar_url?: string } ``` -------------------------------- ### @requestBody Examples Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Examples illustrating the use of the @requestBody decorator for defining request body structures, including models, validators, relations, and custom JSON. ```APIDOC ## @requestBody Examples ### Description Examples illustrating the use of the `@requestBody` decorator for defining request body structures, including models, validators, relations, and custom JSON. ### Usage - `@requestBody // Expects model specification` - `@requestBody // Expects validator specification` - `@requestBody .with(relations) // Expects model and its relations` - `@requestBody .append("some":"valid json") // append additional properties to a Model` - `@requestBody {"foo": "bar"} // Expects a specific JSON` ``` -------------------------------- ### Complete AutoSwagger Configuration Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/06-configuration-guide.md A comprehensive configuration object for AutoSwagger, including paths, OpenAPI info, route settings, behavior options, security schemes, and common parameters/headers. ```typescript // config/swagger.ts import path from "node:path" import url from "node:url" export default { // Paths path: path.dirname(url.fileURLToPath(import.meta.url)) + "/../", // OpenAPI info info: { title: "E-Commerce API", version: "2.1.0", description: "RESTful API for online store management", contact: { name: "API Support", email: "api-support@example.com" }, license: { name: "MIT" } }, // Route configuration tagIndex: 2, ignore: ["/swagger", "/docs", "/health", "/metrics", "*/test"], preferredPutPatch: "PUT", // Behavior snakeCase: true, debug: process.env.DEBUG === "true", persistAuthorization: true, fileNameInSummary: false, productionEnv: "production", // Security authMiddlewares: ["auth", "auth:api", "auth:jwt"], defaultSecurityScheme: "BearerAuth", securitySchemes: { BearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" }, ApiKeyAuth: { type: "apiKey", in: "header", name: "X-API-Key" } }, // Common parameters and headers common: { parameters: { pagination: [ { in: "query", name: "page", schema: { type: "number", example: 1 } }, { in: "query", name: "limit", schema: { type: "number", example: 20 } } ], sorting: [ { in: "query", name: "sort", schema: { type: "string", example: "created_at" } }, { in: "query", name: "order", schema: { type: "string", enum: ["asc", "desc"], example: "desc" } } ] }, headers: { paginated: { "X-Total-Count": { description: "Total number of results", schema: { type: "integer", example: 1234 } }, "X-Page": { description: "Current page", schema: { type: "integer", example: 1 } }, "X-Per-Page": { description: "Results per page", schema: { type: "integer", example: 20 } }, "X-Total-Pages": { description: "Total pages", schema: { type: "integer", example: 62 } } }, rateLimit: { "X-RateLimit-Limit": { description: "Requests per minute", schema: { type: "integer", example: 1000 } }, "X-RateLimit-Remaining": { description: "Remaining requests", schema: { type: "integer", example: 992 } } } } } } ``` -------------------------------- ### Get product by ID Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/08-complete-example.md Retrieves a specific product by its unique identifier. ```APIDOC ## GET /api/v1/products/{id} ### Description Retrieves a specific product by its ID. ### Method GET ### Endpoint /api/v1/products/{id} ### Parameters #### Path Parameters - **id** (number) - Required - The unique identifier of the product. ### Response #### Success Response (200) - **(object)** - The product object. #### Response Example ```json { "id": 1, "name": "MacBook Pro", "price": 1999.99, "category": { "id": 1, "name": "Electronics" } } ``` ``` -------------------------------- ### Get product by ID Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/08-complete-example.md Retrieve a single product with all its details and category information. ```APIDOC ## GET /products/:id ### Description Retrieve a single product with all its details and category information. ### Method GET ### Endpoint /products/:id ### Parameters #### Path Parameters - **id** (number) - Required - Product ID ### Response #### Success Response (200) - **Product** - Product found with category information #### Response Example { "id": 1, "name": "Example Product", "description": "This is an example product.", "status": "active", "category_id": 1, "created_at": "2023-01-01T00:00:00.000Z", "updated_at": "2023-01-01T00:00:00.000Z", "category": { "id": 1, "name": "Example Category" } } #### Error Response (404) Product not found. #### Error Response (401) Unauthorized access. ``` -------------------------------- ### ExampleGenerator Class Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md The ExampleGenerator class is used to generate example values for OpenAPI documentation based on provided schemas. ```APIDOC ## ExampleGenerator Class ### Constructor ```typescript constructor(schemas: any) ``` **Parameters:** - `schemas` (object): Map of available schemas. ``` -------------------------------- ### GET /products Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Returns an array of products and their relations. Supports sorting and filtering. ```APIDOC ## GET /products ### Description Returns array of products and it's relations. ### Method GET ### Endpoint /products ### Parameters #### Query Parameters - **sortBy** (string) - Optional - Description for sortBy - **sortType** (string) - Optional - Description for sortType ### Response #### Success Response (200) - **Product[]** (array) - Array of products with relations - **X-Total-Pages** (integer) - Total amount of pages - **X-Total** (integer) - Total amount of results - **X-Per-Page** (integer) - Results per page - **X-pages** (string) - A description of the header ``` -------------------------------- ### Parse Schema Reference with ExampleGenerator Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Parses schema references to generate example data, optionally returning only the example value. Use this for complex schema references including relations and exclusions. ```typescript parseRef(line: string, exampleOnly?: boolean): object | any ``` ```typescript // Single model with relations const ref1 = generator.parseRef(".with(posts, profile)") // Returns: { content: { "application/json": { schema: ..., example: {...} } } } ``` ```typescript // Array with exclusion const ref2 = generator.parseRef(".exclude(internalId)") ``` ```typescript // Paginated results const ref3 = generator.parseRef(".paginated()") // Returns pagination structure with data and meta ``` ```typescript // Just the example value const ref4 = generator.parseRef("", true) // Returns: { id: 1, name: "John", email: "john@example.com" } ``` -------------------------------- ### Define Query Parameters with Type and Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/05-annotations-guide.md Use @paramQuery to define query parameters for filtering or pagination. Metadata like @type and @example can be used to specify the data type and provide a default or sample value. ```typescript /** * @paramQuery page - Page number - @type(number) * @paramQuery limit - Results per page - @type(number) @example(20) * @paramQuery search - Search term - @type(string) */ public async index() {} ``` -------------------------------- ### Controller Annotation Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/01-overview.md Demonstrates how to use JSDoc comments with @ directives in controllers to enrich API documentation, including summary, description, parameters, and responses. ```typescript /** * @summary Get all products * @description Returns an array of products with optional filtering * @paramQuery page - Current page number - @type(number) * @responseBody 200 - .with(relations) * @responseBody 404 * @tag products */ public async index() {} ``` -------------------------------- ### Basic Setup for Swagger UI and Docs Routes Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/README.md Configure routes in AdonisJS v6 to serve Swagger UI and the raw OpenAPI JSON. Requires importing AutoSwagger and your swagger configuration. ```typescript // routes.ts import AutoSwagger from "adonis-autoswagger" import swagger from "#config/swagger" router.get("/swagger", async () => { return AutoSwagger.docs(router.toJSON(), swagger) }) router.get("/docs", async () => { return AutoSwagger.ui("/swagger", swagger) }) ``` -------------------------------- ### Controller Method Documentation with Adonis AutoSwagger Tags Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Example of documenting controller methods using JSDoc tags for operations, parameters, responses, and request bodies. ```typescript export default class SomeController { /** * @index * @operationId getProducts * @description Returns array of producs and it's relations * @responseBody 200 - .with(relations) * @paramUse(sortable, filterable) * @responseHeader 200 - @use(paginated) * @responseHeader 200 - X-pages - A description of the header - @example(test) */ public async index({ request, response }: HttpContextContract) {} /** * @show * @paramPath id - Describe the path param - @type(string) @required * @paramQuery foo - Describe the query param - @type(string) @required * @description Returns a product with it's relation on user and user relations * @responseBody 200 - .with(user, user.relations) * @responseBody 404 */ public async show({ request, response }: HttpContextContract) {} /** * @update * @responseBody 200 * @responseBody 404 - Product could not be found * @requestBody */ public async update({ request, response }: HttpContextContract) {} /** * @myCustomFunction * @summary Lorem ipsum dolor sit amet * @paramPath provider - The login provider to be used - @enum(google, facebook, apple) * @responseBody 200 - {"token": "xxxxxxx"} * @requestBody {"code": "xxxxxx"} */ public async myCustomFunction({ request, response }: HttpContextContract) {} } ``` -------------------------------- ### AdonisJS v5 AutoSwagger Setup Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Set up AutoSwagger for AdonisJS v5 to generate and serve API documentation. This includes routes for both the raw Swagger YAML and the interactive Swagger UI. ```javascript import AutoSwagger from "adonis-autoswagger"; import swagger from "Config/swagger"; // returns swagger in YAML Route.get("/swagger", async () => { return AutoSwagger.docs(Route.toJSON(), swagger); }); // Renders Swagger-UI and passes YAML-output of /swagger Route.get("/docs", async () => { return AutoSwagger.ui("/swagger", swagger); }); ``` -------------------------------- ### AdonisJS v6 AutoSwagger Setup Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Set up AutoSwagger for AdonisJS v6 to generate and serve API documentation. This includes routes for both the raw Swagger YAML and the interactive Swagger UI. ```javascript import AutoSwagger from "adonis-autoswagger"; import swagger from "#config/swagger"; // returns swagger in YAML router.get("/swagger", async () => { return AutoSwagger.default.docs(router.toJSON(), swagger); }); // Renders Swagger-UI and passes YAML-output of /swagger router.get("/docs", async () => { return AutoSwagger.default.ui("/swagger", swagger); // return AutoSwagger.default.scalar("/swagger"); to use Scalar instead. If you want, you can pass proxy url as second argument here. // return AutoSwagger.default.rapidoc("/swagger", "view"); to use RapiDoc instead (pass "view" default, or "read" to change the render-style) }); ``` -------------------------------- ### Custom OpenAPI Specification Processing Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/07-utilities-reference.md Example demonstrating how to fetch, modify, and serve an OpenAPI specification. It shows adding a custom endpoint and converting the spec to YAML. ```typescript import AutoSwagger from "adonis-autoswagger" import { formatOperationId } from "adonis-autoswagger/helpers" // Get spec and modify const spec = await AutoSwagger.json(router.toJSON(), config) // Add custom endpoint spec.paths["/custom"] = { get: { operationId: formatOperationId("CustomController.test"), summary: "Custom endpoint", responses: { 200: { description: "OK" } } } } // Convert to YAML and serve const yaml = AutoSwagger.jsonToYaml(spec) return yaml ``` -------------------------------- ### Generate Docs and Build for Production Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Execute the necessary commands to generate documentation, build the production-ready application, and copy the swagger configuration file. ```bash node ace docs:generate node ace build --production cp swagger.yml build/ ``` -------------------------------- ### Configure Swagger for AdonisJS v6 Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Create a configuration file for Adonis AutoSwagger. This example shows configuration for AdonisJS v6, including path resolution using node:path and node:url. ```typescript // for AdonisJS v6 import path from "node:path"; import url from "node:url"; // --- export default { // path: __dirname + "/../", for AdonisJS v5 path: path.dirname(url.fileURLToPath(import.meta.url)) + "/../", // for AdonisJS v6 title: "Foo", // use info instead version: "1.0.0", // use info instead description: "", // use info instead tagIndex: 2, productionEnv: "production", // optional info: { title: "title", version: "1.0.0", description: "", }, snakeCase: true, debug: false, // set to true, to get some useful debug output ignore: ["/swagger", "/docs"], preferredPutPatch: "PUT", // if PUT/PATCH are provided for the same route, prefer PUT common: { parameters: {}, // OpenAPI conform parameters that are commonly used headers: {}, // OpenAPI conform headers that are commonly used }, securitySchemes: {}, // optional authMiddlewares: ["auth", "auth:api"], // optional defaultSecurityScheme: "BearerAuth", // optional persistAuthorization: true, // persist authorization between reloads on the swagger page showFullPath: false, // the path displayed after endpoint summary }; ``` -------------------------------- ### Create new product Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/08-complete-example.md Creates a new product in the system. ```APIDOC ## POST /api/v1/products ### Description Creates a new product. ### Method POST ### Endpoint /api/v1/products ### Request Body - **(object)** - Required - Product data for creation. ### Response #### Success Response (201) - **(object)** - The created product object. #### Response Example ```json { "id": 1, "name": "MacBook Pro", "price": 1999.99, "category": { "id": 1, "name": "Electronics" } } ``` ``` -------------------------------- ### Main Export Usage Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/01-overview.md Demonstrates how to import and use the `AutoSwagger` singleton instance to generate API documentation. ```APIDOC ## Main Export ```typescript import AutoSwagger from "adonis-autoswagger" // AutoSwagger is a singleton instance, ready to use const spec = await AutoSwagger.docs(routes, config) ``` ``` -------------------------------- ### ValidatorParser.validatorToObject() Example Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/03-parsers-reference.md An example demonstrating how to use validatorToObject to convert a Vine validator schema for email and password into an OpenAPI schema. ```typescript import vine from "@vinejs/vine" const schema = vine.object({ email: vine.string().email(), password: vine.string().minLength(8) }) const openApiSchema = await validatorParser.validatorToObject(schema) // Returns: // { // type: "object", // properties: { // email: { type: "string", format: "email", example: "user@example.com" }, // password: { type: "string", minLength: 8, example: "password123" } // }, // required: ["email", "password"], // description: "Schema (Validator)" // } ``` -------------------------------- ### Append Enum Field Example to Response Body Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Use `.append(enumFieldExample)` to add enum field examples when defining response bodies. ```typescript @responseBody 200 - .with(relations).append(enumFieldExample) ``` -------------------------------- ### Add Docs Generation to Build Script Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/10-troubleshooting.md Integrate documentation generation and file copying into your build script for automated deployment. ```bash #!/bin/bash npm run build NODE_ENV=production node ace docs:generate cp swagger.* build/ ``` -------------------------------- ### Serve Pre-generated Documentation in Production Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/08-complete-example.md Configures a route to serve the pre-generated documentation files in a production environment. This route reads the swagger.yml file when NODE_ENV is set to production. ```typescript router.get("/swagger", async () => { // NODE_ENV=production → reads swagger.yml return AutoSwagger.docs(router.toJSON(), swagger) }) ``` -------------------------------- ### Check package.json Imports Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/10-troubleshooting.md Use cat and grep to display the 'imports' section and the 10 lines following it in the package.json file. ```bash cat package.json | grep -A 10 '"imports"' ``` -------------------------------- ### Import and Use Main Export Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/README.md Import the AutoSwagger singleton instance and use the `docs` method to generate the OpenAPI specification. Ensure `routes` and `config` are properly defined. ```typescript import AutoSwagger from "adonis-autoswagger" // Use the singleton instance const spec = await AutoSwagger.docs(routes, config) ``` -------------------------------- ### @requestFormDataBody Examples Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/README.md Examples for using the @requestFormDataBody decorator to define form data request bodies, including raw JSON schemas and models with appended fields. ```APIDOC ## @requestFormDataBody Examples ### Description Examples for using the `@requestFormDataBody` decorator to define form data request bodies, including raw JSON schemas and models with appended fields. ### Usage #### Providing a raw JSON ```json @requestFormDataBody {"name":{"type":"string"},"picture":{"type":"string","format":"binary"}} // Expects a valid OpenAPI 3.x JSON ``` #### Providing a Model, and adding additional fields ```json @requestFormDataBody // Expects a valid OpenAPI 3.x JSON @requestFormDataBody .exclude(property1).append("picture":{"type":"string","format":"binary"}) // Expects a valid OpenAPI 3.x JSON ``` ``` -------------------------------- ### Create new product Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/08-complete-example.md Create a new product entry. All required fields must be provided. The product will be created in 'active' status by default. ```APIDOC ## POST /products ### Description Create a new product entry. All required fields must be provided. The product will be created in 'active' status by default. ### Method POST ### Endpoint /products ### Request Body - **name** (string) - Required - Product name - **description** (string) - Required - Product description - **price** (number) - Required - Product price - **category_id** (number) - Required - ID of the category ### Request Example { "name": "New Gadget", "description": "A brand new gadget with amazing features.", "price": 99.99, "category_id": 2 } ### Response #### Success Response (201) - **Product** - Product created successfully with category information #### Response Example { "id": 2, "name": "New Gadget", "description": "A brand new gadget with amazing features.", "status": "active", "category_id": 2, "created_at": "2023-01-02T10:00:00.000Z", "updated_at": "2023-01-02T10:00:00.000Z", "category": { "id": 2, "name": "Electronics" } } #### Error Response (422) Validation failed - {"errors": [{"field": "string", "message": "string"}]} #### Error Response (401) Unauthorized access. ``` -------------------------------- ### Serve Alternative UI Documentation with AdonisJS Routes Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/02-api-reference.md Configure routes to serve alternative UI documentation formats like Scalar or RapiDoc. The Swagger UI configuration is not required for Scalar. ```typescript // Serve Alternative UI // Alternative: Scalar UI router.get("/docs-scalar", async () => { return AutoSwagger.scalar("/swagger") }) // Alternative: RapiDoc router.get("/docs-rapidoc", async () => { return AutoSwagger.rapidoc("/swagger", "read") }) ``` -------------------------------- ### Verify Model and Validator File System Presence Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/10-troubleshooting.md Use the `ls` command to confirm that your model, validator, interface, and type files exist in their expected directories within the `app/` folder. ```bash # Verify models ls -la app/models/ # Verify validators ls -la app/validators/ # Verify interfaces ls -la app/interfaces/ # Verify types/enums ls -la app/types/ ``` -------------------------------- ### Copy Swagger Files to Build Output Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/10-troubleshooting.md Manually copy 'swagger.yml' and 'swagger.json' to your build directory if they are not included automatically. ```bash # ✗ swagger.yml not in build/ # ✓ Copy it: cp swagger.yml build/ cp swagger.json build/ ``` -------------------------------- ### Create new product Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/05-annotations-guide.md Creates a new product. Requires valid product data and returns the created product upon success. ```APIDOC ## POST /products ### Description Create new product. Requires valid product data and returns the created product upon success. ### Method POST ### Endpoint /products ### Request Body - **product** (CreateProductValidator) - Product data for creation ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (201) - **product** (Product) - Created successfully #### Response Example ```json { "example": "response body" } ``` #### Error Response (422) - **message** (string) - Validation failed ``` -------------------------------- ### Generated JSON Schema for User Model Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/09-schema-discovery.md The OpenAPI schema generated from the example AdonisJS User model. ```json { "User": { "type": "object", "required": ["email", "password"], "properties": { "id": { "type": "number" }, "email": { "type": "string", "format": "email", "example": "john@example.com" }, "password": { "type": "string", "minLength": 8 }, "role": { "type": "string", "enum": ["user", "admin", "moderator"] }, "name": { "type": "string", "example": "John Doe" }, "avatar_url": { "type": "string", "format": "uri" }, "posts": { "type": "array", "items": { "$ref": "#/components/schemas/Post" } }, "created_at": { "type": "string", "format": "date-time" }, "updated_at": { "type": "string", "format": "date-time" } } } } ``` -------------------------------- ### Generated OpenAPI Schemas from TypeScript Interfaces Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/09-schema-discovery.md Shows the resulting OpenAPI schema definitions generated from the example TypeScript interfaces. ```json { "PaginatedResponse": { "type": "object", "properties": { "data": { "type": "array" }, "meta": { "$ref": "#/components/schemas/PaginationMeta" } } }, "UserProfile": { "type": "object", "properties": { "id": { "type": "number" }, "email": { "type": "string", "format": "email" }, "name": { "type": "string" }, "bio": { "type": "string" }, "avatar_url": { "type": "string", "format": "uri" } } } } ``` -------------------------------- ### Verify Schema Source File Paths Source: https://github.com/ad-on-is/adonis-autoswagger/blob/main/_autodocs/10-troubleshooting.md Use the find command to check if schema source directories like 'models', 'validators', 'interfaces', or 'types' exist within the 'app' directory. ```bash # Check each schema source exists: find app -type d -name models -o -name validators -o -name interfaces -o -name types ```