百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
A

adonis-autoswagger

> 编程语言
开源

为 AdonisJS 自动生成 Swagger 文档

197 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

为 AdonisJS 自动生成 Swagger 文档

Adonis AutoSwagger

Auto-Generate swagger docs for AdonisJS

️ Install

bash
pnpm i adonis-autoswagger #using pnpm

⭐️ Features

  • Creates paths automatically based on routes.ts
  • Creates schemas automatically based on app/Models/*
  • Creates schemas automatically based on app/Interfaces/*
  • Creates schemas automatically based on app/Validators/* (only for adonisJS v6)
  • Creates schemas automatically based on app/Types/* (only for adonisJS v6)
  • Rich configuration via comments
  • Works also in production mode
  • node ace docs:generate command

✌️Usage

Create a file /config/swagger.ts

…

In your routes.ts

6️⃣ for AdonisJS v6

…

5️⃣ for AdonisJS v5

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);
});

️ Done

Visit http://localhost:3333/docs to see AutoSwagger in action.

Functions

  • async docs(routes, conf): get the specification in YAML format
  • async json(routes, conf): get the specification in JSON format
  • ui(path, conf): get default swagger UI
  • rapidoc(path, style): get rapidoc UI
  • scalar(path, proxyUrl): get scalar UI
  • stoplight(path, theme): get stoplight elements UI
  • jsonToYaml(json): can be used to convert json() back to yaml

Compatibility

For controllers to get detected properly, please load them lazily.

typescript
✅ const TestController = () => import('#controllers/test_controller')
❌ import TestController from '#controllers/test_controller'

‍ Advanced usage

Additional configuration

info See Swagger API General Info for details.

securitySchemes

Add/Overwrite security schemes Swagger Authentication for details.

typescript
// example to override ApiKeyAuth
securitySchemes: {
  ApiKeyAuth: {
    type: "apiKey"
    in: "header",
    name: "X-API-Key"
  }
}

defaultSecurityScheme

Override the default security scheme.

  • BearerAuth
  • BasicAuth
  • ApiKeyAuth
  • your own defined under securitySchemes

authMiddlewares

If a route uses a middleware named auth, auth:api, AutoSwagger will detect it as a Swagger security method. However, you can implement other middlewares that handle authentication.

Modify generated output

typescript
Route.get("/myswagger", async () => {
  const json = await AutoSwagger.json(Route.toJSON(), swagger);
  // modify json to your hearts content
  return AutoSwagger.jsonToYaml(json);
});

Route.get("/docs", async () => {
  return AutoSwagger.ui("/myswagger", swagger);
});

Custom Paths in adonisJS v6

AutoSwagger supports the paths set in package.json. Interfaces are expected to be in app/interfaces. However, you can override this, by modifying package.json as follows.

json
//...
"imports": {
  // ...
  "#interfaces/*": "./app/custom/path/interfaces/*.js"
  // ...
}
//...

Configure

tagIndex

Tags endpoints automatically

  • If your routes are /api/v1/products/... then your tagIndex should be 3
  • If your routes are /v1/products/... then your tagIndex should be 2
  • If your routes are /products/... then your tagIndex should be 1

ignore

Ignores specified paths. When used with a wildcard (*), AutoSwagger will ignore everything matching before/after the wildcard. /test/_will ignore everything starting with/test/, whereas \*/testwill ignore everything ending with/test.

common

Sometimes you want to use specific parameters or headers on multiple responses.

Example: Some resources use the same filter parameters or return the same headers.

Here's where you can set these and use them with @paramUse() and @responseHeader() @use(). See practical example for further details.


Extend Controllers

Add additional documentation to your Controller-files

@summary (only one) A summary of what the action does

@tag (only one) Set a custom tag for this action

@description (only one) A detailed description of what the action does.

@operationId (only one) An optional unique string used to identify an operation. If provided, these IDs must be unique among all operations described in your API..

@responseBody (multiple)

Format: - -

can be either a, / or a custom JSON {}

@responseHeader (multiple)

Format: - - -

@paramType (multiple)

Type can be one of Parameter Types (first letter in uppercase)

@requestBody (only one) A definition of the expected requestBody

Format: ``

can be either a, /, or a custom JSON {}

@requestFormDataBody (only one) A definition of the expected requestBody that will be sent with formData format.

Schema A model or a validator. Format: ``

Custom format

Format: {"fieldname": {"type":"string", "format": "email"}} This format should be a valid openapi 3.x json.


Examples

@responseBody examples

…

@paramPath and @paramQuery examples

typescript
// basicaly same as @response, just without a status
@paramPath  - Description - (meta)
@paramQuery  - Description - (meta)

@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)

@requestBody examples

typescript
// basicaly same as @response, just without a status
@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

@requestFormDataBody examples

typescript
// Providing a raw JSON
@requestFormDataBody {"name":{"type":"string"},"picture":{"type":"string","format":"binary"}} // Expects a valid OpenAPI 3.x JSON
typescript
// Providing a Model, and adding additional fields
@requestFormDataBody  // Expects a valid OpenAPI 3.x JSON
@requestFormDataBody .exclude(property1).append("picture":{"type":"string","format":"binary"}) // Expects a valid OpenAPI 3.x JSON

Practical example

config/swagger.ts

…

app/Controllers/Http/SomeController.ts

…

What does it do?

AutoSwagger tries to extracat as much information as possible to generate swagger-docs for you.

Paths

Automatically generates swagger path-descriptions, based on your application routes. It also detects endpoints, protected by the auth-middlware.

Responses and RequestBody

Generates responses and requestBody based on your simple Controller-Annotation (see Examples)


Schemas

Models

Automatically generates swagger schema-descriptions based on your models

Interfaces

Instead of using param: any you can now use custom interfaces param: UserDetails. The interfaces files need to be located at app/Interfaces/

Enums

If you use enums in your models, AutoSwagger will detect them from app/Types/ folder and add them to the schema. If you want to add enum on ExampleValue, you can use .append(enumFieldExample)

Example:

typescript
 @responseBody 200 - .with(relations).append(enumFieldExample)

Extend Models

Add additional documentation to your Models properties.

SoftDelete

Either use compose(BaseModel, SoftDeletes) or add a line @swagger-softdeletes to your Model.

Attention

The below comments MUST be placed 1 line above the property.


@no-swagger Although, autoswagger detects serializeAs: null fields automatically, and does not show them. You can use @no-swagger for other fields.

@enum(foo, bar) If a field has defined values, you can add them into an enum. This is usesfull for something like a status field.

@format(string) Specify a format for that field, i.e. uuid, email, binary, etc...

@example(foo bar) Use this field to provide own example values for specific fields

@props({"minLength": 10, "foo": "bar"}) Use this field to provide additional properties to a field, like minLength, maxLength, etc. Needs to bee valid JSON.

@required Specify that the field is required

typescript
// SomeModel.js
@hasMany(() => ProductView)
// @no-swagger
public views: HasMany

@column()
// @enum(pending, active, deleted)
public status: string

@column()
// @example([email protected])
public email: string

@column()
// @props({"minLength": 10})
public age: number

Production environment

[!WARNING] Make sure NODE_ENV=production in your production environment or whatever you set in options.productionEnv

To make it work in production environments, additional steps are required

  • Create a new command for docs:generate See official documentation

    • This should create a new file in commands/DocsGenerate.ts
  • Use the provided DocsGenerate.ts.examle/DocsGeneratev6.ts.example and put its contents into your newly created DocsGenerate.ts

  • Modify /start/env.ts as follows

typescript
//...
// this is necessary to make sure that the `DocsGenerate` command will run in CI/CD pipelines without setting environment variables
const isNodeAce = process.argv.some(
  (arg) => arg.endsWith("/ace") || arg === "ace"
);

export default await Env.create(
  new URL("../", import.meta.url),
  isNodeAce
    ? {}
    : {
        // leave other settings as is
        NODE_ENV: Env.schema.enum([
          "development",
          "production",
          "test",
        ] as const),
        PORT: Env.schema.number(),
      }
);

//...
  • Execute the following
bash
node ace docs:generate
node ace build --production
cp swagger.yml build/

Known Issues

  • Interfaces with objects are not working like interface Test {foo: {bar: string}}
    • Solution, just extract the object as it's own interface

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言