/ src / swagger-redoc.ts
swagger-redoc.ts
 1  import swaggerJSDoc, { type Response } from "swagger-jsdoc";
 2  import swaggerUi from "swagger-ui-express";
 3  import type { Application } from "./declarations";
 4  
 5  const swaggerDefinition = {
 6  	openapi: "3.0.0",
 7  	info: {
 8  		title: "Apply Creatures APIs",
 9  		version: "1.0.0",
10  		description:
11  			"This is the OpenAPI docs of this server, you may try out any endpoint from here. You may create a user, then authenticate, to be able to invoke protected endpoints. There is also RedDoc, which is generated from the swagger spec",
12  	},
13    components: {
14      securitySchemes: {
15        bearerAuth: {
16          type: "http",
17          scheme: "bearer",
18          bearerFormat: "JWT",
19        },
20      },
21    },
22    security: [
23      {
24        bearerAuth: [],
25      },
26    ],
27  };
28  
29  const options = {
30  	swaggerDefinition,
31  	apis: ["./src/**/*.ts"],
32  };
33  
34  const swaggerSpec = swaggerJSDoc(options);
35  
36  export default (app: Application): void => {
37  	app.use("/docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
38  
39  	// Redoc setup
40  	app.use("/redoc", (_: Request, res: Response) => {
41  		res.send(`
42          <!doctype html>
43          <html>
44            <head>
45              <title>ReDoc</title>
46              <!-- needed for adaptive design -->
47              <meta charset="utf-8"/>
48              <meta name="viewport" content="width=device-width, initial-scale=1">
49              <!--
50              ReDoc doesn't change outer page styles
51              -->
52              <style>
53                body {
54                  margin: 0;
55                  padding: 0;
56                }
57              </style>
58            </head>
59            <body>
60              <redoc spec-url='/api-docs/swagger.json'></redoc>
61              <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"> </script>
62            </body>
63          </html>
64        `);
65  	});
66  
67  	// Serve the Swagger JSON
68  	app.get("/api-docs/swagger.json", (req: Request, res: Response) => {
69  		res.setHeader("Content-Type", "application/json");
70  		res.send(swaggerSpec);
71  	});
72  };