ShogunPanda / fastify-openapi-docs

A simple plugin for Fastify that generates OpenAPI spec automatically.
ISC License
27 stars 5 forks source link

Referencing definitions producing errors #9

Closed michelle54725 closed 1 year ago

michelle54725 commented 1 year ago

Hi,

I have a schema that looks like this:

export const VisibilityOptionsSchema = {
  type: 'object',
  $id: 'VisibilityOptions',
  description: "Visibility options for each field in User schema. Allowed values: 'hidden' / 'shown' / 'alwaysShown'.",
  properties: {
    id: { $ref: '#/definitions/options' },
    name: { $ref: '#/definitions/options' },
    sexuality: { $ref: '#/definitions/options' },
    age: { $ref: '#/definitions/options' },
    ...
  },
  additionalProperties: false,
  definitions: {
    options: {
      type: 'string',
      enum: ['hidden', 'shown', 'alwaysShown'],
    },
  },
};

It works as intended as can see here the enum restriction is enforced:

image

However, in OpenAPI we get these errors:

image

The functionality is not affected but any idea why the reference isn't recognized?

ShogunPanda commented 1 year ago

Hi! First of all, sorry for the very late reply.

This is expected as the link is resolved from two different roots: one is your schema in the context of fastify, the other one is the entire document in the context of OpenAPI.

Luckily for you, and completely undocumented (my bad) you can fix this with this workaround:

In your case:

const VisibilityOptionsOptionsSchema = {
  $id: 'definitions-visibilityOptions-options', // Note that here you cannot use / as it is used for path traversing
  type: 'string',
  enum: ['hidden', 'shown', 'alwaysShown']
}

const VisibilityOptionsSchema = {
  $id: 'VisibilityOptions',
  type: 'object',
  description: "Visibility options for each field in User schema. Allowed values: 'hidden' / 'shown' / 'alwaysShown'.",
  properties: {
    id: { $ref: 'definitions-visibilityOptions-options#' } // The # is used by openapi-docs to recognized when we have to manipulate the reference in the generated documentation file.
  },
  additionalProperties: false
}

const server = fastify()
server.addSchema(VisibilityOptionsOptionsSchema)

// Continue

Let me know if this fixes your problem. For now I'm closing the issue.