Giter Club home page Giter Club logo

fastify-oas's People

Contributors

adrai avatar bmullan91 avatar dannyifang avatar dependabot[bot] avatar ehossack avatar fyang1024 avatar jnig avatar johakr avatar jtassin avatar m5m1th avatar mashpie avatar mjwwit avatar olafkrueger avatar schantaraud avatar sheldhur avatar skellla avatar tswaters avatar tuner88 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

fastify-oas's Issues

Use $ref in body or in response

Hi,

Can you provide a sample to use $ref for body or response schema ?
I'm trying lot of thing but nothing works...

Definition.ts

public static Cat = {
        $id: 'Cat',
        type: 'object',
        required: ['id', 'name'],
        properties: {
            _id: { type: 'string', format: 'uuid' },
            name: { type: 'string'},
        }
    };

CatRoute.ts :

{
    method: 'POST',
    url: '/api/cat',
    handler: addCatController,
    schema: addCatSwagger
  }

ControllerCat.ts

  function addCatController = async (req, reply) => {
    try {
      const cat = new CatModel(req.body);
      return cat.save();
    } catch (err) {
      console.error(err);
    }
  }

SwaggerCat.ts

const add = {
    description: `Create a new Cat`,
    tags: ['cat'],
    summary: `Creates new cat with given values`,
    body: {
        in: 'body',
        name: 'body',
        description: 'Pet object that needs to be added to the store',
        required: true,
        schema: {
          $ref: 'Cat'
        }
      }
    ,
    responses: {
      200: {
        description: 'Successful response',
      }
    }
  };

Any any to accept Cat definition in the body of my put request ?
Same thing for returning one Cat ? (array of Cat is ok, but how we do with only one object in return )

Suggest to remove default swagger basePath value

Can I suggest to leave the default basePath value to be an empty string instead of '/'? Currently, the servers URL from the response swagger JSON is always having a trailing slash because of the default value and it doesn't have a way to remove it.

This creates a small problem when importing the JSON file into Postman. Postman can read the swagger JSON and automatically generate all API endpoints. However, the issue here is all the endpoints are having double slash due to the server URL having a trailing slash. To illustrate http://localhost:3000//login.

If we have a way to unset the default basePath or keep the basePath as empty. It would solve the issue.

Default swagger option basePath value:

Example of my swagger JSON from fastify-oas:

{
  "openapi": "3.0.0",
  "info": {
    "title": "API documentation",
    "description": "Test",
    "version": "1.0.0"
  },
  "components": {},
  "servers": [
    {
      "url": "http://localhost:3000/"
    }
  ],
  "paths": {
    ...

(I'm hoping to have a way to remove the trailing slash from the server url)

Generate spec to a file without running the instance

Hello,

Thank you for your contribution @SkeLLLa

I have a question. It's possible to generate a spec file/documentation/json to file system? I need it to generate a OpenAPI client in a CI pipeline.

Currently, I'm doing like this:

export const exportOpenApiSpec = (): void =>
  app.listen(port, host, (err) => {
    if (err) {
      app.log.error(err)
      process.exit(1)
    }

    const spec = JSON.stringify(app.oas())
    writeFile('api-client/spec.json', spec, (err) => {
      if (err) return app.log.error(err)
      app.log.info('Exported with success')
      process.exit(0)
    })
  })

It is possible to do it without running a fastify instance?

Thank you

Fastify 3.x Upgrade

Hello,

Where can I send a PR to upgrade this package to fastify 3.x? GitHub or GitLab?

TY

CSP error

Swagger:

Content Security Policy: The page’s settings blocked the loading of a resource at eval (“script-src”).

Redoc:

Content Security Policy: The page’s settings blocked the loading of a resource at eval (“script-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at blob:http://localhost/e69d7b8c-3e5b-4efc-a496-b415b0146d56 (“script-src”).

Deprecated Schema Key is not supported

Deprecated Schema Key is not supported.

Expected: A route with a parameter marked as deprecated: true would get the deprecated key in the resulting open api documentation.

Actual: deprecated is not in the allowed keys and so is not included in the documentation.

Generated example does not contain properties of type "oneOf"

I have a schema like this

{
    "type": "object",
    "properties": {
        "monitor": {
            "type": "object",
            "properties": {
                "status": {
                    "oneOf": [
                        {
                            "type": "string",
                            "enum": ["ok"]
                        },
                        {
                            "type": "string",
                            "enum": ["ko"]
                        }
                    ]
                }
            },
            "required": ["status"]
        }
    },
    "required": ["monitor"]
}

generated with the nice library https://github.com/sinclairzx81/typebox but the generated example looks like

{
  "monitor": {}
}

whereas the interactive schema shows monitor* -> status* -> oneOf -> etc

For bigger schema it can be a problem because user easily jump on the example as documentation, and missing attributes are just ignored, MIA...

Option to generate references instead of replacing reference

I am trying to use oneOf for code generation and the output is not what I am expecting. I traced the root cause of the issue and I think is related with fact that fastify-oas is replacing my references.

For example:

fastify.addSchema({
        $id: "Cat",
        type: "object",
        properties: { name: { type: "string" } }
});
fastify.addSchema({
        $id: "Dog",
        type: "object",
        properties: { legs: { type: "integer" } }
});

Used in a route:

animal: {
  oneOf: [
     "Cat#",
     "Dog#"
  ]
}

As result I am getting for the path:

animal: {
  oneOf: [
      {
        type: "object",
        properties: { name: { type: "string" } }
     },
     {
        type: "object",
        properties: { legs: { type: "integer" } }
    }
  ]
}

It would be nice to have the option to get the references instead (like using $ref)

Support Fastify v3

Hello,
when updating fastify to v3 i get this error:

Error: fastify-plugin: fastify-oas - expected '>=2.0.0 <2.12.0 || >=2.12.1 <3.0.0' fastify version, '3.0.2' is installed

When using Netlify Functions, throwing error

Hello and thanks.
Here some logs

Error during invocation:  TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:107:11)
    at Object.dirname (path.js:1121:5)
    at resolve (webpack-internal:///../node_modules/app-root-path/lib/resolve.js:82:22)
    at module.exports (webpack-internal:///../node_modules/app-root-path/lib/app-root-path.js:6:20)
    at Object.eval (webpack-internal:///../node_modules/app-root-path/index.js:4:18)
    at eval (webpack-internal:///../node_modules/app-root-path/index.js:5:30)
    at Object.../node_modules/app-root-path/index.js (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:3569:1)
    at __webpack_require__ (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:20:30)
    at eval (webpack-internal:///../node_modules/fastify-oas/lib/openapi/constructor.js:4:14)
    at Object.../node_modules/fastify-oas/lib/openapi/constructor.js (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:5263:1)
    at __webpack_require__ (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:20:30)
    at eval (webpack-internal:///../node_modules/fastify-oas/lib/openapi/index.js:1:21)
    at Object.../node_modules/fastify-oas/lib/openapi/index.js (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:5274:1)
    at __webpack_require__ (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:20:30)
    at eval (webpack-internal:///../node_modules/fastify-oas/lib/index.js:2:17)
    at Object.../node_modules/fastify-oas/lib/index.js (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:5252:1)

Bearer auth not work

Hi,
First of all, thanks for great plugin, I am new to Fastify and on my way to create the first API system on it.
However, after many tries I cannot setup swagger to use Bearer auth, can you please give some example on how to archive that?

Many thanks.

JS object serialisation issue

I've defined an object property in response schema as below:

taxes: {
   type: 'string',
   additionalProperties: {
      type: 'number'
   }
}

The JS object property value in response data is like

taxes: { stampDuty: 0.12 }

Expected data in response:

"taxes": {
   "stampDuty": 0.12
}

Actual data in response:

"taxes": "[object Object]"

How to use this plugin?

Hi,

Need help to understand what does it means by "Unlike regular OpenAPI spec you'll still need some options from swagger 2.0" from https://github.com/SkeLLLa/fastify-oas#openapi

What is this "some options" to be precise?

I have difficulty using this plug-in at the moment... browsing to base_url/documentation return 404. Appreciate if it is possible, please upload an example illustrating how petstore in openapi version 3.0 can be serve from fastify-oas? Understood that this plugin only show the document (ReDoc?) and will not implement the spec.

Thanks.

Support for multiple request examples

Hiya

I notice I can include a single request example by using the example property on the body.
But what if I want multiple?

Can I propose the allowing of a property like responseExamples that would set the content[mediaType].examples property, similar to the way example is handled in https://github.com/SkeLLLa/fastify-oas/blob/master/lib/helpers.js#L98

Alternatively use the examples array as is provided, and extract the name property:

 else if (body.examples) {
      dst.content[mediaType].examples = Object.fromEntries(
          body.examples.map(({ name, ...rest }) => [name, rest])
      );
      delete body.examples;
    }

Multiple types not supported

Awesome library! I have completely autogenerated docs thanks to this repo 💪

One thing I believe I have stumbled across is that you can't have multiple types e.g:

Note: SwaggerHelper.modelToSwaggerProps is just a method that maps Sequelize model datatypes to Swagger datatypes

const {ProjectUsers, Projects} = require('my-sequelize-model-repo')

fastify.addSchema({
  $id: 'projectUser',
  type: 'object',
  properties: Object.assign(
    SwaggerHelper.modelToSwaggerProps(ProjectUsers, true)[ProjectUser],
    {
      Project: {
        type: ['object', 'null'],
        nullable: true,
        properties: SwaggerHelper.modelToSwaggerProps(Projects)[Project]
      }
    }
  )
})

Which will generate...

{
 '$id': 'projectUser',
  type: 'object',
  properties: {
     id: { type: 'integer' },
     user_id: { type: 'integer' },
     project_id: { type: 'integer' },
     notes: { type: 'string' },
     occurred_at: { type: 'string', format: 'date-time' },
     created_at: { type: 'string', format: 'date-time' },
     updated_at: { type: 'string', format: 'date-time' },
     deleted_at: { type: 'string', format: 'date-time' },
     Project: {
         type: ['object', 'null'],
         nullable: true,
         properties: {
            id: { type: 'integer' },
            name: { type: 'string' }
         }
     }
  }
}

Note the attempt to get the child association (Project) to be either an object or null

I think this was also caught in another implementation: AfterShip/swagger-ajv#19

This has got me in quite the pickle because Ajv (the default json validator with fastify) isn't happy with if the Project model is null if I just keep the type as 'object'. This configuration works in the API response through Ajv - but it breaks in swagger docs

image

image

File upload ui dialog?

I am wondering how to get the swagger-ui for my server let me do an 'upload-file' request/form. Any ideas or suggestions? I have gotten this type of thing to work in non-js projects that have swagger docs before.

FastifySchema is not correct when using Fastify 3.x

export const opts: RouteShorthandOptions = {
  schema: {
    tags: ["organization"],
    params: baseParamsSchema,    
    response: {
      200: organizationSchema,
    },
  },
 
  preValidation: [],
  preHandler: [],
};

results in

Type
{ tags: string[]; 
    params: { 
      description: string; 
      type: string; 
      properties: { 
          organizationId: {    
              type: string; 
              title: 
              string; 
          }; 
      }; 
    required: string[]; $schema: string; };
    response: { 
        200: { 
            description: string; 
            type: string; 
            properties: { ...; };
            required: string[]; 
            $schema: string; 
          
        }; 
      
    }; 
}
is not assignable to type 'FastifySchema'.
Object literal may only specify known properties, 
and 'tags' does not exist in type 'FastifySchema'.

But tags is a part of schema in fastify 3.x, can u resolve? To circumvent I am using @ts-ignore

Context
node version: v15.12.0
fastify version: >=^3.14.0
fastify-oas: ^3.0.8
os: Windows, Ubuntu WSL

Fetch Error: Internal Server Error

In my project my intention is to configure fastify-swagger with OpenAPI version 3.0.0 with the following configuration:

I am using fastify-oas as fastify plugin such that my existing configuration does not need to alter.

const swaggerConfig = {
    swagger: {
      info: {
        title: `${constants.SERVICE_NAME.toUpperCase()} swagger`,
        description: `NetApp ${constants.SERVICE_NAME.toUpperCase()} service API.`,
        version: '1.0.0'
      },
      externalDocs: {
        url: 'https://swagger.io',
        description: 'Find more info here'
      },
      schemes: [`${schema}`],
      consumes: ['application/json'],
      produces: ['application/json'],
      tags: [
        { name: 'persistence', description: 'foo' },
        { name: 'index', description: 'bar'}
      ],
      securityDefinitions: {
        Authorization_Token: {
            type: 'apiKey',
            name: 'Authorization',
            in: 'header'
        }
      }
    },
    exposeRoute: true,
    routePrefix: `${constants.EXTERNAL_PATH}/api-docs`
};

fastify.register(require('fastify-oas'), swaggerConfig );

Actually I was trying to following the following link here (https://github.com/fastify/fastify-swagger/blob/master/examples/dynamic-openapi.js).

However somehow I am not able to succeed, always it shows the error that it's not able to load the swagger. Not seeing any error in the console. The error is like below screen shot:

enter image description here

Any clue how can I debug would be helpful how can I proceed with debugging this.

One interesting point is: as I am removing arbitrarily some portion of the schema just to see if I can pin point by trial and error, it's start working!

So if there a way to bit systematically debug it, would be great.

Thanks,
Pradip

Required body attributes don't show as required in the model view of the body doc

Hi there !

I just noticed that when tagging an attribute of the body as required, in the swagger html view, the little red star that indicates that the field is required in the body doesn't show on the given field.

image

Commenting this line in the code solves the problem and the required fields display as expected in the swagger view.

Do you have any insight on this behavior ? I mean, why deleting the body.required ?

Thanks in advance for your answer ;)

And thank you for your efforts on this plugin and keep up the good work ! 👍

Could not resolve reference: Failed to fetch

I originally thought this might be related to #30, however I now do not think it is.

I'm using Fastify v2.14.1, and I instantiate my own AJV and configure it using .addSchema(...). I then use the $id references from my manually loaded schemas when creating my route schemas. This works fine in Fastify, and I can tell the schemas are being validated at runtime.

However, when using the plugin UI, and navigating into a particular route, I get the following error, when the schema reference is attempted to be resolved.

Resolver error at paths./events.post.requestBody.content.application/json.schema.properties.rulesets.items.$ref
Could not resolve reference: Failed to fetch

The $ref I am using is a full URL with hostname, but I would expect the plugin to lookup the reference using AJV where it is registered, instead of attempting to fetch. Perhaps this is the wrong expectation?

addModels param doesn't do what expected.

I've tried using addModels: true param to enable models view on the UI, although It seems to be not really documented and neither having any effects when setting this to true.

item objects in schemas are not stripped of allowed props

Hi. Thanks for the great library.

I noticed a bug when using common schemas via $ref. Being a fastily schema, they'll have an $id property. Normally this gets trimmed out in the allowedProps function with objects/properties but that doesn't seem to happen with array/items.

Using following schema:

fastily.addSchema({
  $id: 'MyBusinessObject',
  type: 'object',
  properties: {}
})

const schema =  {
  type: 'array',
  items: {
    $ref: 'MyBusinessObject#'
  }
};

The following oas document for this section is generated, which raises warnings for having additional properties, $id:

{
  "type": "array",
  "items": {
    "$id": "MyBusinessObject",
    "type": "object",
    "properties": {}
  }
}

I've got a fix for it and will be sending a PR shortly.

Expose only one documentation UI

Is there a way to only expose one of the two UIs? I prefer one over the other and would like to share specific doc URLs with team members and it would be simpler if I could disable one of the two and use /documentation/index.html for the only one loaded up.

Remove custom properties

In AJV you can add custom properties and validation rules. However, when you generate the json/yaml through fastify-oas, these will be included. Is there a way to filter these?

Dynamic host and urls base on request

Api schema may change such as server information on openapi 3 base on multiple domains.
Not static one during register plugin.
How could we handle it ?

"servers": // ??,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.