在 nodejs 开发 API 时,使用 swagger 生成文档很方便,但是默认的样式看起来不是特别漂亮。而 scalar 为我们提供了很好的界面。今天我们就一起把它集成到 nestjs 中。
很简单,效果也很棒!
后续的 API 文档还是参考
@nestjs/swagger
,这个插件只是更改了一下 UI 展示🤣
我们看下效果先:
默认的 Swagger 插件生成的 API 文档
使用 scalar 包装后的 API 文档
使用前的基础操作
我们先引入 nestjs 提供的 swagger 插件。这里我把 swagger 插件抽离到一个单独的 setup-swagger 文件中,后续有关 API 文档的全局改动我们只需要在这里修改。
import { NestExpressApplication } from '@nestjs/platform-express';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { apiReference } from '@scalar/nestjs-api-reference';
export function setupSwagger(app: NestExpressApplication, port: number) {
const config = new DocumentBuilder()
.setTitle('Nest starter')
.setDescription('Symbol Nest setup template')
.setVersion('1.0')
.build();
const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs-api', app, documentFactory, {
jsonDocumentUrl: 'swagger/json', // 这里在 swagger/json 地址生成 swagger 的 json 文件,后续我们会使用
});
console.log(`docs start on http://localhost:${port}/docs-api`);
}
在 main.ts 中使用
async function bootstrap() {
// ...其他内容
const port = Number(process.env.PORT || 3000);
setupSwagger(app, port);
await app.listen(port);
}
引入 scalar
我们可以在它的 GitHub 文档中找到 nestjs 相关的配置。
接下来我们改造之前的 setup-swagger.ts
文件
import { NestExpressApplication } from '@nestjs/platform-express';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { apiReference } from '@scalar/nestjs-api-reference';
export function setupSwagger(app: NestExpressApplication, port: number) {
const config = new DocumentBuilder()
.setTitle('Nest starter')
.setDescription('Symbol Nest setup template')
.setVersion('1.0')
.build();
const documentFactory = () => SwaggerModule.createDocument(app, config);
SwaggerModule.setup('docs-api', app, documentFactory, {
jsonDocumentUrl: 'swagger/json',
});
app.use(
'/reference',
apiReference({
url: '/swagger/json',
theme: 'default',
layout: 'modern',
targetKey: 'JavaScript',
clientKey: 'Axios',
}),
);
// 这里我们改变文档地址,使用 scalar 来展示 API 文档
console.log(`docs start on http://localhost:${port}/reference`);
}
这里的一些配置解释
- theme: 是 scalar 提供的一些主题,包括
'alternate'| 'default'| 'moon'| 'purple'| 'solarized'| 'bluePlanet'| 'deepSpace'| 'saturn'| 'kepler'| 'elysiajs'| 'fastify'| 'mars'| 'laserwave'| 'none'
- layout:
modern
是左右两栏,classic
就是类似于默认 swagger 的样式 - targetKey: 默认请求示例的语言,这里使用 JavaScript
- clientKey: 默认请求示例的插件,这里我们使用 Axios
更多的配置可以查看 configuration
结语
这样就完成啦,是不是很简单呢?快去试一下吧,将你的 API 文档美化一下。