preface
A few days ago, SWAGger was integrated in the project. When everything was ready and I was planning to deploy swagger to the server, I found that it did not go well. When I visited, the page went blank.
After a few twists and turns, I have finally solved this problem. In this article, I would like to share my solution with you and welcome interested developers to read this article.
Integrated Swagger
First, we install three dependency packages through YARN, as follows:
yarn add @nestjs/swagger swagger-ui-express fastify-swagger
Copy the code
After the installation is complete, we open the project entry file main.ts and add the following code:
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
async function bootstrap() {
// **** other code omitted ****
const config = new DocumentBuilder()
.setTitle("nest-demo")
.setDescription("Nest-demo API Usage Documentation")
.setVersion("1.0.0")
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("api", app, document);
}
Copy the code
Next, we start the project, in your browser to http://127.0.0.1:3000/api, the display interface as shown below:
default
The options list all the interfaces in our project
Write interface documentation through annotations
In the @nestjs/ Swagger library, it provides rich dependencies for us to use and generates friendly interface documentation for us. Here are a few common annotations:
@ApiTags
Annotations to describe the Controller layer.@ApiOperation
Annotations that describe a specific interface in a controller.@ApiProperty
Annotations to describe the parameters of the DTO layer.@ApiResponse
Annotations that describe the data returned by the interface.
Please refer to my project code for specific usage of the above annotations, as follows:
- AppController.ts
- AppDto.ts
- ResultVO
After the above configuration, the final access effect is as follows:
For more information on how to use swagger annotations, see OpenAPI (Swagger).
Deploying to the Server
Next, we need to package the project and deploy it to the server. This project is built using a single file method. For developers who are not familiar with this, please go to: The best way to deploy Nest project.
Problems encountered during build
Because with Swagger in, ERROR in./node_modules/@nestjs/mapped-types/dist/type-helpers.utils. Js 69:27-63 Module not found: ERROR: Can’t resolve ‘class-transformer/storage’ in …
After a bit of searching, we found the answer in the Issues of the Mapped -types repository. We needed to add class-Transformer /storage to the lazyImports in webpack.config.js and ignore them when packaging. Complete code please move:
module.exports = {
entry: "./src/main".target: "node".// ** Other configuration code omitted **
plugins: [
// The plug-in to ignore
new webpack.IgnorePlugin({
checkResource(resource) {
const lazyImports = [
"@nestjs/microservices"."@nestjs/microservices/microservices-module"."@nestjs/websockets/socket-module"."cache-manager"."class-validator"."class-transformer"."class-transformer/storage"]; })}Copy the code
For the complete code, go to webpack.config.js
Problems encountered during deployment
We deployed the project to the server, started it, and when the browser accessed Swagger through 127.0.0.1:3000 / API, the page went blank, and when we opened the console, some of its resource files were 404.
This is a tricky problem, and my gut tells me it must be because I’m configuring single-file deployment. After asking a lot of people for help and doing a lot of research, I find that none of them have played the same game as I have. They all rely on NPM install to run nest projects on the server.
Is really bad a big cake 🤡, I became the first person to eat crab, in front of a blue sea waiting for me to explore.
After some thinking, webpack packed all dependencies into main.js, swagger-ui reference file should be relative path, so it caused the 404 problem, with this question in mind, I opened the source code of Swagger-UI-Express. There is a catch in index.js: it is indeed a relative path to import.
Since it is a relative path and does not have the file under its own package, it must have been imported from another package.
After going through the source code, I found that it also requires a Swagger-UI-dist.
Sure enough, the resource bundles it relies on are all in this directory, so why would he do that? I also hold doubt opened the swagger – UI warehouse, in the docs/usage/installation. It tells the reason in the md, provides a webpack configuration scheme.
After opening the link to the project, I saw the copy-webpack-plugin in the webpack configuration file, and then I had an idea. What it does is to copy the swagger-uI-dist file to dist, which solves the problem that it can’t find the file relative to the path.
With the solution in place, you can happily write code as follows:
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: "./src/main".target: "node".plugins: [
new CopyWebpackPlugin({
patterns: [
// Copy swagger related files
{
from: __dirname + "/node_modules/swagger-ui-dist/".to: ". /"}]}]}Copy the code
After rebuilding, we found swagger-uI-Dist files in dist directory. We started the project and found swagger’s interface could be normally seen in the browser again.
Careful developers may find that swagger-UI-dist has a lot of useless files in it, polluting our dist directory, and we need to clean them up after packing them up.
! [image-20220318112446885](/Users/likai/Library/Application Support/typora-user-images/image-20220318112446885.png)
Next, the clean-Webpack-plugin comes into play. We add the following code to the webPack configuration file:
- CleanAfterEveryBuildPatterns meaning in constructing a complete after deleting files
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: "./src/main".target: "node".plugins: [
// ** other code omitted **
// Delete unnecessary files
new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: [
__dirname + "/dist/*.html",
__dirname + "/dist/*.map",
__dirname + "/dist/*.md",
__dirname + "/dist/*.json",
__dirname + "/dist/index.js",
__dirname + "/dist/LICENSE",
__dirname + "/dist/NOTICE"]]}})Copy the code
Now the dist directory looks a lot more comfortable 😼
Note: copy-webpack-plugin and clean-webpack-plugin need to be installed in the devDependencies dependency using YARN.
For the complete code, go to webpack.config.js
Deployment to YAPI
Finally, we imported Swagger data from the data management module of YAPI. We thought it was smooth, but it reported an error: the returned data format was not JSON.
After leafing through the files, I found itplan, the original is to add after the address-json
.
After adding, you can smoothly import into yAPI, done 🤗
It’s so hard to be the first mover that I’ve opened so many tabs in my browser 🌚 to solve this problem
Project code
For the full code used in this article, go to the project’s GitHub repository: Nest-Project
Write in the last
At this point, the article is shared.
I’m an amazing programmer, a front-end developer.
If you are interested in me, please visit my personal website for further information.
- If there are any errors in this article, please correct them in the comments section. If this article helped you, please like it and follow 😊
- This article was first published in the magic programmer public number, without permission to prohibit reprinting 💌