I'm working on a Node.js project using Fastify with TypeScript, and I'm trying to generate API documentation using Swagger for multiple versions of my API ('v1' and 'v2'). I have opted to use the @fastify/swagger
along with @fastify/swagger-ui
plugins.
Here's what I have so far:
import { FastifyInstance } from 'fastify';
import fp from 'fastify-plugin';
import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUi from '@fastify/swagger-ui';
const supportedVersions = ['v1', 'v2'];
/**
* @description These plugins add self-generated documentation based on route schemas
* @see https://www.npmjs.com/package/@fastify/swagger
* @see https://www.npmjs.com/package/@fastify/swagger-ui
*/
export default fp(async (fastify: FastifyInstance) => {
supportedVersions.forEach(async (version) => {
await fastify.register(async function (fastify) {
await fastify.register(fastifySwagger);
await fastify.register(fastifySwaggerUi, {
routePrefix: `/${version}/documentation`,
uiConfig: {
docExpansion: 'full',
deepLinking: false,
},
transformSpecification: (swaggerObject, request, reply) => {
let tempSwaggerObject: Record<string, any> = swaggerObject;
let version = request.url.split('/').find((item) => item.startsWith('v'));
tempSwaggerObject.info = {
title: 'Test',
description: `Test API documentation for version ${version}`,
version: `${version}`,
};
let tempPaths = tempSwaggerObject.paths;
Object.keys(tempPaths).forEach((path) => {
if (path !== `/${version}/`) {
delete tempPaths[path];
}
});
tempSwaggerObject.paths = { ...tempPaths };
return tempSwaggerObject;
},
transformSpecificationClone: true,
});
});
});
});
This setup successfully creates the following URLs for the different versions of the API documentation:
http://127.0.0.1:4000/v1/documentation/static/index.html
http://127.0.0.1:4000/v2/documentation/static/index.html
However, the Swagger UI is not picking up the schemas from the routes, there is at least a GET method in each route for testing, but the generated documentation is empty:
The project's folder structure is as follows:
I'm using @fastify/swagger@8.4.0, @fastify/swagger-ui@1.8.1, @fastify/autoload@5.7.1, fastify@4.17.0, and fastify-plugin@4.5.0.
Has anyone encountered a similar issue? I would greatly appreciate any insights on properly configuring Swagger with Fastify to serve multiple versions of API documentation.