我需要获取我在ApiGateway中所有API的文档,但我只能看到最后一个API的文档。这是我的课:
import Auth from '@aws-amplify/auth';
import { config } from './config';
import APIGateway, { GetExportRequest } from 'aws-sdk/clients/apigateway';
import { ICredentials } from '@aws-amplify/core';
import { Spec, SwaggerUIBundle } from 'swagger-ui-dist'
export const initSwagger = async (): Promise<void> => {
const credentials = await Auth.currentCredentials();
const apiGateway = createAPIGatewayClient(credentials);
const specs = await getAPIGatewaySpec(apiGateway);
renderUI(specs);
};
const createAPIGatewayClient = (credentials: ICredentials): APIGateway => new APIGateway({
region: config.region,
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken,
});
const getAPIGatewaySpec = async (apiGateway: APIGateway): Promise<Spec[]> => {
const { items: apis } = await apiGateway.getRestApis().promise();
const data = await getAPIExports(apiGateway, apis);
if (!data) {
throw new Error('No documentation body received');
}
const blobToJson = function (binArray: any) {
const jsons = new Array();
for (let j = 0; j < binArray.length; j++) {
let str = '';
for (let i = 0; i < binArray[j].body.length; i++) {
str += String.fromCharCode(parseInt(binArray[j].body[i]));
}
jsons.push(JSON.parse(str));
}
return jsons;
};
const specs = blobToJson(data) as Spec[];
console.log('spec: ', specs)
console.log('spec.length: ', specs.length)
specs.forEach((spec) => {
spec.servers.forEach((server: { variables: { basePath: { default: string } } }) => {
const basePath = server.variables.basePath.default;
if (basePath.startsWith('/')) {
server.variables.basePath.default = basePath.substr(1);
}
});
});
return specs;
};
const getAPIExports = async (apiGateway: APIGateway, apis: APIGateway.ListOfRestApi | undefined) => {
if (!apis) return;
return Promise.all(
apis.map(async (api) => {
const req: GetExportRequest = {
restApiId: api.id,
stageName: config.apiGateway.stageName,
exportType: 'oas30',
accepts: 'application/json',
} as GetExportRequest;
return await apiGateway.getExport(req).promise();
}),
);
};
const renderUI = (specs?: Spec[]): void => {
if (!specs) {
return;
}
specs.forEach((spec) => {
SwaggerUIBundle({
spec: spec,
'dom_id': '#swagger',
deepLinking: true,
openapi: '3.0.0',
});
});
};
规范包含我的 API 的所有规范,它看起来像这样:
规格:
(4) [{…}, {…}, {…}, {…}]
0: {openapi: '3.0.1', info: {…}, servers: Array(1), paths: {…}, components: {…}}
1: {openapi: '3.0.1', info: {…}, servers: Array(1), paths: {…}, components: {…}}
2: {openapi: '3.0.1', info: {…}, servers: Array(1), paths: {…}, components: {…}}
3: {openapi: '3.0.1', info: {…}, servers: Array(1), paths: {…}, components: {…}}
但是,当我尝试访问其他 API 的文档时,我只能看到数组中最后一个位置(位置 3)的规范。这让我相信 SwaggerUIBundle 在迭代过程中被覆盖了。即使我不迭代数组,我仍然会得到相同的结果。有办法解决这个问题吗?提前谢谢你。
编辑:
顺便说一句,我正在使用这个实现并进行一些修改:https://github.com/m-radzikowski/aws-swaggerui