fastify に swagger を組み込みたい
@fastify/swagger 組み込む
plugin が用意されてるので導入していく
とりあえず必要最低限を準備してみる。
options は色々あるが、全て optional なので省く。
import fastifySwagger from '@fastify/swagger';
import Fastify from 'fastify';
const fastify = Fastify();
fastify.register(fastifySwagger);
実行しても何も起きない...
Following plugins serve swagger/openapi front-ends based on the swagger definitions generated by this plugin:
@fastify/swagger-ui
As of version 8 @fastify/swagger is only responsible for generating valid swagger/openapi-specifications. The new @fastify/swagger-ui plugin is responsible for serving the swagger-ui frontend.
Options in version 7 of @fastify/swagger related to the configuration of the swagger-ui frontend are now options of @fastify/swagger-ui.
The exposeRoute option is removed.
UI を表示するためには、別途 @fastify/swagger-ui
を組み込む必要があるのか...
巷の tutorial では、古い version のfastify-swagger
を使ってたりするから、この点は注意だな...
@fastify/swagger-ui 組み込む
import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUi from '@fastify/swagger-ui';
import Fastify from 'fastify';
const fastify = Fastify();
fastify.register(fastifySwagger);
fastify.register(fastifySwaggerUi);
async function main() {
await fastify.listen({
port: 3000,
host: '0.0.0.0',
});
}
main().catch(console.error);
いけた!
http://0.0.0.0:3000/documentation にアクセスすると swagger ui 表示される↓
あとは適宜 options を設定していけば OK かな
endpoint 追加してみる
fastify.addSchema({
$id: 'createUseSchema',
type: 'object',
required: ['name'],
properties: {
name: {
type: 'string',
},
},
});
fastify.post('/user', {
schema: {
body: { $ref: 'createUseSchema#' },
response: {
201: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' },
},
},
},
},
handler: async (
request: FastifyRequest<{
Body: {
name: string;
age: number;
};
}>,
reply: FastifyReply,
) => {
const body = request.body;
return reply.code(201).send(body);
},
});
Model しか swagger ui には反映されない...
user routes を register してみる
const userRoutes = async (server: FastifyInstance) => {
server.addSchema({
$id: 'createUseSchema',
type: 'object',
required: ['name'],
properties: {
name: {
type: 'string',
},
},
});
server.post('/', {
schema: {
body: { $ref: 'createUseSchema#' },
response: {
201: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' },
},
},
},
},
handler: async (
request: FastifyRequest<{
Body: {
name: string;
age: number;
};
}>,
reply: FastifyReply,
) => {
const body = request.body;
return reply.code(201).send(body);
},
});
};
fastify.register(userRoutes, { prefix: 'users' });
いけた!