Skip to content

快速開始

tsp-asyncapiTypeSpecAsyncAPI 3.1 emitter。你用 TypeSpec 描述事件驅動 API。emitter 會為你產出 AsyncAPI 文件。

環境需求

  • Node.js >= 20
  • pnpm(本專案的 devEngines 欄位鎖定 ^11)

安裝

在你的 TypeSpec 專案中安裝這個套件:

bash
pnpm add tsp-asyncapi

產出第一份 AsyncAPI 文件

建立 main.tsp

typespec
import "tsp-asyncapi";

using AsyncAPI;

@service(#{ title: "Order Service API" })
@info(#{
  version: "1.0.0",
  description: "This is a sample Order Service event-driven API.",
  contact: #{ name: "API Support", email: "support@example.com" },
  license: #{ name: "MIT", url: "https://opensource.org/licenses/MIT" }
})
@tag("orders")
@tag("payment")
@externalDocs("https://example.com/docs", "Service Documentation")
namespace Orders;

tspconfig.yaml 設定 emitter:

yaml
emit:
  - "tsp-asyncapi"
options:
  "tsp-asyncapi":
    asyncapi-id: "urn:com:example:orders"
    default-content-type: "application/json"

執行編譯:

bash
tsp compile .

輸出檔在 tsp-output/tsp-asyncapi/asyncapi.yaml。以下是上面範例實際的完整輸出

yaml
asyncapi: 3.1.0
id: urn:com:example:orders
info:
  title: Order Service API
  version: 1.0.0
  description: This is a sample Order Service event-driven API.
  contact:
    name: API Support
    email: support@example.com
  license:
    name: MIT
    url: https://opensource.org/licenses/MIT
  tags:
    - name: payment
    - name: orders
  externalDocs:
    url: https://example.com/docs
    description: Service Documentation
defaultContentType: application/json
channels: {}
operations: {}
components: {}

每一行從哪來

輸出欄位來源
idemitter 選項 asyncapi-id
info.title@service(#{ title: ... })
info.versiondescriptioncontactlicensetermsOfService@info(#{ ... })
info.description(後備)namespace 上的 @doc/** ... */ 文件註解。只在 @info 沒給 description 時使用。
info.tags每個 @tag 產生一筆
info.externalDocs@externalDocs(url, description?)
defaultContentTypeemitter 選項 default-content-type

若沒有 @service,文件仍會輸出。info 後備為 { title: "AsyncAPI Document", version: "0.0.0" }。若程式裡有多個 @service,emitter 發出 multiple-services 警告並採用第一個。

下一步