在Linux环境下,要实现Swagger API文档的国际化,你需要遵循以下步骤:
npm install -g swagger-jsdoc
创建Swagger配置文件:在你的项目中创建一个名为swagger.js
的文件。在这个文件中,我们将配置Swagger以支持多语言。
配置多语言支持:在swagger.js
文件中,你需要配置swagger-jsdoc
选项以支持多语言。例如:
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerOptions = {
swaggerDefinition: {
info: {
title: 'My API',
description: 'My API with internationalization support',
version: '1.0.0',
contact: {
name: 'Your Name',
},
},
},
apis: ['./src/routes/*.js'], // Your API routes file path
additionalModels: ['./src/models/*.js'], // Your API models file path
lang: 'en', // Default language
};
module.exports = swaggerJsDoc(swaggerOptions);
i18n
的文件夹。在这个文件夹中,为每种支持的语言创建一个子文件夹(例如en
、zh
等)。在每个子文件夹中,创建一个名为swagger.json
的文件,其中包含该语言的API文档翻译。例如,在i18n/en/swagger.json
中:
{
"info": {
"title": "My API",
"description": "My API with internationalization support",
"version": "1.0.0"
},
"paths": {
"/api/v1/users": {
"get": {
"summary": "Get a list of users",
"responses": {
"200": {
"description": "A list of users"
}
}
}
}
}
}
在i18n/zh/swagger.json
中:
{
"info": {
"title": "我的API",
"description": "支持国际化的我的API",
"version": "1.0.0"
},
"paths": {
"/api/v1/users": {
"get": {
"summary": "获取用户列表",
"responses": {
"200": {
"description": "用户列表"
}
}
}
}
}
}
swagger.js
文件中,添加对多语言文件的支持。例如:const swaggerJsDoc = require('swagger-jsdoc');
const fs = require('fs');
const path = require('path');
const swaggerOptions = {
swaggerDefinition: {
info: {
title: 'My API',
description: 'My API with internationalization support',
version: '1.0.0',
contact: {
name: 'Your Name',
},
},
},
apis: ['./src/routes/*.js'],
additionalModels: ['./src/models/*.js'],
lang: 'en',
};
const swaggerDocs = {};
// Load i18n files
const i18nDir = path.join(__dirname, 'i18n');
fs.readdirSync(i18nDir).forEach((lang) => {
if (lang !== 'en') { // Skip default language folder
swaggerDocs[lang] = require(path.join(i18nDir, lang, 'swagger.json'));
}
});
module.exports = swaggerJsDoc(swaggerOptions, { swaggerDocs });
swagger-ui-express
中间件来显示Swagger文档。例如:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// Your API routes
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
现在,当你访问http://localhost:3000/api-docs
时,你应该能看到Swagger UI界面。要切换语言,只需在URL中添加?lang=zh
(例如)。
这就是在Linux环境下实现Swagger API文档国际化的方法。你可以根据需要添加更多语言,并在i18n
文件夹中的相应文件中进行翻译。