Bắt đầu nhanh
Hướng dẫn này trình bày ba cách phổ biến nhất: hàm hỗ trợ curlToOpenApi, hàm postmanToOpenApi và lớp XToOpenApi cho cấu hình tùy chỉnh.
Điều kiện tiên quyết: cài đặt gói. Cài đặt
ghi chú
Tất cả hàm chuyển đổi đều bất đồng bộ và trả về ConvertResult. Luôn dùng await.
1. Chuyển đổi lệnh curl
Truyền một lệnh curl vào curlToOpenApi. Trường document của kết quả chứa đối tượng OpenAPI 3.2 được tạo.
import { curlToOpenApi } from "@powerduck/x-to-openapi";
const result = await curlToOpenApi(
`curl -X POST https://api.example.com/users \
-H 'Content-Type: application/json' \
--data '{"name":"Ada","age":36}'`,
);
console.log(JSON.stringify(result.document, null, 2));
Dưới đây là phần trích từ tài liệu được tạo:
{
"openapi": "3.2.0",
"info": { "title": "Generated API", "version": "1.0.0" },
"servers": [{ "url": "https://api.example.com" }],
"paths": {
"/users": {
"post": {
"operationId": "postUsers",
"tags": ["users"],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" }
},
"required": ["name", "age"]
}
}
}
},
"responses": { "default": { "description": "Successful response" } }
}
}
}
}
Kiểm tra chuyển đổi có thành công không và xem thông tin chẩn đoán:
if (!result.ok) {
for (const d of result.diagnostics) {
console.error(`[${d.severity}] ${d.code}: ${d.message}`);
}
}
console.log("Document valid:", result.documentValid);
2. Chuyển đổi bộ sưu tập Postman
Truyền đối tượng bộ sưu tập đã phân tích cú pháp hoặc chuỗi JSON vào postmanToOpenApi. Tập lệnh kiểm thử được giữ lại trong x-postman-scripts.
import { postmanToOpenApi } from "@powerduck/x-to-openapi";
const collection = {
info: {
name: "User API",
schema: "https://schema.postman.com/json/collection/v2.1.0/collection.json",
},
item: [
{
name: "Get user",
request: {
method: "GET",
url: "https://api.example.com/users/123",
header: [{ key: "Authorization", value: "Bearer token" }],
},
event: [
{
listen: "test",
script: {
type: "text/javascript",
exec: ["pm.test('status is 200', () => pm.response.to.have.status(200));"],
},
},
],
},
],
auth: { type: "bearer", bearer: [{ key: "token", value: "{{token}}" }] },
};
const result = await postmanToOpenApi(collection, {
title: collection.info.name,
inferPathParameters: true,
});
// The Postman test script survives on the operation:
console.log(result.document.paths["/users/123"]?.get?.["x-postman-scripts"]);
Bạn cũng có thể dùng chuỗi JSON:
const fromText = await postmanToOpenApi('{"info":{"name":"API"},"item":[]}');