Can't get swagger to pick up fastify routes

62 views Asked by At

My swagger config isn't picking up any of my routes for some reason.

I can access the swagger UI but just get No operations defined in spec! when I navigate to http://127.0.0.1:8181/documentation. I'm sure I had this set up working at some point, maybe a version has changed. I've tried changing the order in which things are initiated to no avail.

Can anyone help?

Thanks

my server.js

const { logger } = require('./log.js')
const cors = require('@fastify/cors')
const swagger = require('@fastify/swagger')
const swaggerUi = require('@fastify/swagger-ui')
const fastify = require('fastify')({ logger: true })

const port = 8181

const initializeFastify = () => {
  fastify.register(cors, {
    origin: true,
    methods: ['GET', 'POST', 'OPTIONS']
  })

  fastify.register(swagger, {
    swagger: {
      info: {
        title: 'OpenAPI spec for the ICAT Upload Service',
        description: 'The Upload service allows a DataGateway user to upload files to the ICAT archive by adding datafiles to an existing dataset. ' +
                    'It provides an endpoint to create a dataset',
        version: 'beta',
        consumes: ['application/json'],
        produces: ['application/json']
      }
    }
  })

  fastify.register(swaggerUi, {
    routePrefix: '/documentation'
  })

  fastify.addContentTypeParser('application/offset+octet-stream', (request, payload, done) => done(null))

  addHealthCheckEndpoint()

  fastify.listen({ port, host: '0.0.0.0' }, onServerStart)
}

const addHealthCheckEndpoint = () => {
  fastify.route({
    method: 'get',
    url: '/',
    schema: {
      description: 'The following endpoint has been created to detect a running service',
      tags: ['Hello World'],
      response: {
        201: {
          description: 'Successful response',
          type: 'object'
        }
      }
    },
    handler: async (request, reply) => {
      reply.statusCode = 200
      reply.send('Hello World')
    }
  })
}

const onServerStart = (err) => {
  logger.info(`--> Starting Upload server, listening on port: ${port}`)
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}

module.exports = fastify.server

initializeFastify()
1

There are 1 answers

0
WhatTheWhat On

The route needs to be registered:

 fastify.register(async function (fastify) {
    addHealthCheckEndpoint()
  })