Git Product home page Git Product logo

joi-route-to-swagger's Introduction

joi-route-to-swagger

2.0.0 is out

It's a breaking change.

The dependency of joi-to-json has been upgraded to its 2.x version. The jsonSchemaToSwagger API once exported has no value as the joi-to-json has provided the conversion logic.

Philosophy

Most programmers are not so willing to write documentations. Also, the fact is that documentation is easily rotted as time goes by with changing requirement.

How to maintain documentation is a long-lasting problem in software engineering. Hence, there raises a perspective that our written code should be self-documented. What does it mean? If you are not familiar with this concept, please take a visit on Wiki and Martin Fowler's article.

Objective

This tool provides Node.js application an option to keep their API doc up to date.

API doc serves a very important role for the communication between parties implementing the frontend and backend. Besides better naming and reasonable url path, API query/body/param description and restriction are the most important parts. They are also the part that is changed more often due to requirement change.

How can we make the API docs self-documented and kept up to date? If the API docs can be automatically updated once the code is changed, it would be fantastic.

In order to achieve this, we need a documentary approach to define our API with the support of the powerful tools Swagger and joi. Let's see how we achieve this in Usage section below.

Installation

npm install joi-route-to-swagger --save

Usage

Route Definition

A documentary approach to define route is like the sample code below. Although this example is used in my Express.js project, it can also be applied to project using restify, hapi, etc.

The main purpose is to use a descriptive JSON to describe what your routes look like, including its path, description, middlewares, validation criteria, sample response, etc.

const joi = require('joi')

function dummyMiddlewareA() { }
function dummyMiddlewareB() { }
function dummyMiddlewareC() { }

const moduleRouteDef = {
  basePath: '/hero',
  description: 'Hero related APIs',
  routes: [
    {
      method: 'get',
      path: '/',
      summary: 'List',
      description: '',
      action: dummyMiddlewareA,
      validators: {
        query: joi.object().keys({
          productId: joi.string().example('621'),
          sort: joi.string().valid('createdAt', 'updatedAt').default('createdAt'),
          direction: joi.string().valid('desc', 'asc').default('desc'),
          limit: joi.number().integer().max(100).default(100),
          page: joi.number().integer()
        }).with('sort', 'direction')
      },
      responseExamples: [
        {
          code: 200,
          data: {
            err: null,
            data: {
              records: [
                {
                  _id: '59ba1f3c2e9787247e29da9b',
                  updatedAt: '2017-09-14T06:18:36.786Z',
                  createdAt: '2017-09-14T06:18:36.786Z',
                  nickName: 'Ken',
                  avatar: '',
                  gender: 'Male'
                }
              ],
              totalCount: 1,
              page: 1
            }
          }
        }
      ]
    },
    {
      method: 'post',
      path: '/',
      summary: 'Create',
      description: '',
      action: [dummyMiddlewareB, dummyMiddlewareC],
      validators: {
        body: joi.object().keys({
          nickName: joi.string().required().example('鹄思乱想').description('Hero Nickname'),
          avatar: joi.string().required(),
          gender: joi.string().valid('Male', 'Female', ''),
          skills: joi.array().items(joi.string()).example(['teleport', 'invisible'])
        })
      }
    }
  ]
}

module.exports = moduleRouteDef

Converting Route Definition to OpenAPI

Once you have defined your API routes as above, you can use this tool to convert it to OpenAPI in JSON format.

const convert = require('joi-route-to-swagger').convert
const sampleRoutes = require('./test/fixtures/mockA-routes')

const swaggerDocs = convert([sampleRoutes])

Test & Generate Sample OpenAPI

Executes below test command will:

  1. Converts all the routes definition file with -routes.js suffix in test/fixtures/ folder to a OpenAPI schema JSON.
  2. Validate the converted JSON against OpenAPI 3.0.
  3. Generate the OpenAPI JSON to a file in test/sample_api_doc.json.

npm run test

View Generated API Document

Executes below command will startup a static server to host the sample OpenAPI locally:

npm run ui

http://localhost:8080/swagger-ui/index.html

OpenAPI Sample

Of course, you can also download the Swagger UI to host the API routes docs for yourself.

Enjoy.

License

MIT

joi-route-to-swagger's People

Contributors

aokomyshan avatar kenchen-cs avatar kenspirit avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

joi-route-to-swagger's Issues

joi.when() is not working

For joi.when() schema proper swagger definition is not coming for example

Joi schema:-
myRequiredField: rm.joi.boolean(),
message: rm.joi.when('myRequiredField', {
is: true,
then: rm.joi.string(),
otherwise: rm.joi.number(),
})

Actual swagger definition:-
"myRequiredField": {
"type": "boolean",
"description": ""
},
"message": {
"type": [
"array",
"boolean",
"number",
"object",
"string",
"null"
],
"description": ""
}

Expected swagger definition:-

"myRequiredField": {
"type": "boolean",
"description": ""
},
"message": {
"properties": {
"oneOf": [
{
"type": "string"
},
{
"type": "number",
"format": "number"
}
]
}
}

Incorrect reference to entities

Hello,

The current version generates an incorrect reference in the entity defintion.

pet: {
   type: "object",
   description: "",
   schema: {
      $ref: "#/definitions/Pet"
   }
},

The correct version should be:

pet: {
   type: "object",
   description: "",
   $ref: "#/definitions/Pet"
},

Problem with optional params

Hi, guys,
I have the problems with the mapping Joi shemas to Swagger UI and I look for your advices :)

  1. Problem with the optional param
    As you can see below we have optional param "id".
    In case of request body - this parameter shouldn't be visible, because this "id" will be created under the hood.
    In case of response body - this parameter should be visible, because "id" was created at this time.
    I use this common schema both for request and response body:
export const BotSchema = Joi.object().keys({
    id: Joi.string().optional(),
    layout: Joi.number().required().label('bot.navigation.$.layout'),
    title: Joi.string().required().label('bot.navigation.$.title'),
    type: Joi.string().required(),
});

As a result - we can see "id" param in both cases - req and res:
image
What is a right way to working with this schemas?
Should I create different schemas - first for request body and second for response body?

  1. Problem with the incorrect display of the parameters.
    As you can see below I use the next schema for displaying request body:
    image

I see the next picture, but It's incorrect result (we have different types of field "data" depends on field "type".
image
What is a right way to configure this schemas for displaying correct result in Swagger UI?

Thanks in advance!

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.