I try to use fastify/swagger to build my API document, it works and this is my code.
The problem is, it only gets/route2, but cannot get /route1. Any suggestion of it?
'use strict'
const fastify = require('fastify')()
// Define a sample route
fastify.get('/route1', async (request, reply) => {
return { route1: 'world' };
});
const start = async () => {
try {
await fastify.register(require('@fastify/swagger'), {
// openapi 3.0.3 options
openapi: {
...
},
})
// Define a sample route
fastify.get('/route2', async (request, reply) => {
return { route2: 'world' };
});
// Define a sample route
fastify.get('/doc', opts, async (request, reply) => {
reply.send(fastify.swagger())
});
await fastify.ready()
await fastify.listen({ port: 3000 });
console.log(`Server listening on ${fastify.server.address().port}`);
} catch (err) {
console.log(err);
process.exit(1);
}
};
start();
The problem is, it only gets/route2, but cannot get /route1. Any suggestion of it?
fastify-swagger
uses onRoute
hook under the hood.
This means that the hook function is executed synchronous when the event happens. This is explained in detail in my Fastify book.
So, in your code example you are adding the route before registering and awaiting the plugin: await fastify.register(require('@fastify/swagger')
.
So, you must register the fastify-swagger
before adding any routes to the fastify
object instance.
Moreover, the route you created:
fastify.get('/doc', opts, (request, reply) => {
reply.send(fastify.swagger())
});
is the right approach to get the documentation, but since you are using reply.send()
, the handler may be not async
because of this documentation:
https://fastify.dev/docs/latest/Reference/Routes/#promise-resolution