fastify / fastify-swagger

Swagger documentation generator for Fastify
MIT License
915 stars 201 forks source link

Routes doesnt get parsed #812

Closed akama-aka closed 1 month ago

akama-aka commented 1 month ago

Prerequisites

Issue

Hello, ich habe gerade ein problem und zwar werden die Routes von swagger nicht erkannt oder geparsed und ich weiß nicht wirklich warum. Ich hoffe mir kann da wer Helfen:

server.js

////////////////////////////////////////////////////////////////////////////////
//
//                        Other requirements
//
////////////////////////////////////////////////////////////////////////////////
const process = require("node:process");
const { writeFileSync } = require("node:fs");
const { join } = require("node:path");
const Sentry = require("@sentry/node");
require("dotenv").config();
require("./middleware/errorReporting")

////////////////////////////////////////////////////////////////////////////////
//
//                        Fastify Requirements
//
////////////////////////////////////////////////////////////////////////////////
const fastify = require("fastify")({
  logger: true,
});
const errorCodes = fastify.errorCodes;
fastify.register(require("@fastify/postgres"), {
  connectionString: process.env.DATABASE_URL,
})
  .register(require("@fastify/swagger"), {
  yaml: true,
  hideUntagged: false,
  exposeRoute: true,
  mode:'dynamic',
  openapi: {
    openapi: "3.0.0",
    basePath: "",
    schemes: ["http", "https"],
    consumes: ["application/json"],
    produces: ["application/json"],
    info: {
      title: "A title",
      description:
        "A desc",
      version: "1.0.0",
    },
    servers: [
      {
        url: "https://sub.domain.tld",
        description: "A desc",
      },
      {
        url: "https://sub.sub.domain.tld",
        description: "A desc",
      },
    ],
    tags: [
      { name: "tag1", description: "desc1" },
      { name: "tag2", description: "desc2" },
      { name: "tag3", description: "desc3" },
    ],
    components: {
      securitySchemes: {
        authorization: {
          type: "apiKey",
          name: "authorization",
          in: "header",
        },
        "x-auth-agent-token": {
          type: "apiKey",
          name: "x-auth-token",
          in: "header",
        },
      },
    },
  },
});
Sentry.setupFastifyErrorHandler(fastify);
////////////////////////////////////////////////////////////////////////////////
//
//                        ROUTER
//
////////////////////////////////////////////////////////////////////////////////

require(__dirname + "/Controllers/one").forEach(loadRoute);
require(__dirname + "/Controllers/two").forEach(loadRoute);
require(__dirname + "/Controllers/three").forEach(loadRoute);
require(__dirname + "/Controllers/four").forEach(loadRoute);
require(__dirname + "/Controllers/five").forEach(loadRoute);
require(__dirname + "/Controllers/six").forEach(loadRoute);
function loadRoute(routeOptions) {
  fastify.route(routeOptions);
}

fastify.get('/',(req,res) => {
  res.code(404).send();
})
////////////////////////////////////////////////////////////////////////////////
//
//                        FASTIFY LISTENER
//
////////////////////////////////////////////////////////////////////////////////

fastify.listen(
  {
    host: process.env.SERVER_HOST,
    port: 52488,
  },
  async (err) => {
    //const swaggerOutput = JSON.stringify(await fastify.swagger({ yaml: true }), null, 2);
    //writeFileSync("docs/openapi.json", swaggerOutput,"utf-8");
    writeFileSync(
      "docs/openapi.yaml",
      fastify.swagger({ yaml: true }),
      "utf-8",
    );
    if (err) throw err;
  },
);

////////////////////////////////////////////////////////////////////////////////
//
//                        FASTIFY HOOKS
//
////////////////////////////////////////////////////////////////////////////////

fastify.addHook("preHandler", (req, rep, done) => {
  rep.headers({
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET,POST,PATCH,DELETE,OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type,Authorization",
    "Access-Control-Allow-Credentials": "true",
    "X-Content-Type-Options": "nosniff",
    "X-Frame-Options": "DENY",
    "X-XSS-Protection": "1;mode=block",
    "Accept-Patch": "application/json",
    "Accept-Post": "application/json",
  });
  done();
});
fastify.options('/*', (req, res) => {
  return res.headers({
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET,POST,PATCH,DELETE,OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type,Authorization",
    "Access-Control-Allow-Credentials": "true",
    "X-Content-Type-Options": "nosniff",
    "X-Frame-Options": "DENY",
    "X-XSS-Protection": "1;mode=block",
    "Accept-Patch": "application/json",
    "Accept-Post": "application/json",
  }).code(204).send();

})
module.exports = {
  loadRoute
};

Controllers/one.js


module.exports = [
  {
    method: "GET",
    url: "/robots.txt",
    schema: {
      description:"Robots Txt file",
      response:{
        200: {
          description:"Successful response",
          type: "object",
          properties: {
            test: {type:'string'}
          }
        }
      }
    },
    handler: function (req, res) {
      res.headers({ "Content-Type": "text/plain" });
      res.send("User-Agent: *\nDisallow: /");
    },
  },
];
mcollina commented 1 month ago

Wrap your routes in a plugin.

(sorry for the short response, I guess this can unblock you quickly).

akama-aka commented 1 month ago

Wrap your routes in a plugin.

(sorry for the short response, I guess this can unblock you quickly).

okay thank you, I'll try

akama-aka commented 1 month ago

Is there a different possibility? because I dont really want to recode everything into a single function

akama-aka commented 1 month ago

Because I've everything in this schema:

module.exports = [
  {
    method: "GET",
    url: "/robots.txt",
    schema: {
      description:"Robots Txt file",
      response:{
        200: {
          description:"Successful response",
          type: "object",
          properties: {
            test: {type:'string'}
          }
        }
      }
    },
    handler: function (req, res) {
      res.headers({ "Content-Type": "text/plain" });
      res.send("User-Agent: *\nDisallow: /");
    },
  },
  ...
akama-aka commented 1 month ago

Got it thanks