GithubHelp home page GithubHelp logo

rafaph / adonis5-swagger Goto Github PK

View Code? Open in Web Editor NEW

This project forked from reg2005/adonis5-swagger

0.0 1.0 0.0 2.31 MB

Swagger provider for AdonisJS 5

License: MIT License

TypeScript 77.06% HTML 19.66% JavaScript 3.28%

adonis5-swagger's Introduction

adonis5-swagger

Swagger, AdonisJS, SwaggerUI

typescript-image npm-image license-image

Create API documentation easily in Adonis 5 using Swagger

Table of contents

Installation

npm i --save adonis5-swagger

Compile your code:

node ace serve --watch

Connect all dependences:

node ace invoke adonis5-swagger
  • For other configuration, please update the config/swagger.ts.

Sample Usage

  • Add new route:

    Route.get('/api/hello', 'TestController.hello')
  • Create TestController using node ace make:controller Test command:

    import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
    
    export default class TestController {
      /**
      * @swagger
      * /api/hello:
      *   get:
      *     tags:
      *       - Test
      *     summary: Sample API
      *     parameters:
      *       - name: name
      *         description: Name of the user
      *         in: query
      *         required: false
      *         type: string
      *     responses:
      *       200:
      *         description: Send hello message
      *         example:
      *           message: Hello Guess
      */
      public async hello({ request, response }: HttpContextContract) {
        const name = request.input('name', 'Guess')
        return response.send({ message: 'Hello ' + name })
      }
    }
  • You can also define the schema in the Models:

    import { BaseModel } from '@ioc:Adonis/Lucid/Orm'
    
    /** 
    *  @swagger
    *  definitions:
    *    User:
    *      type: object
    *      properties:
    *        id:
    *          type: uint
    *        username:
    *          type: string
    *        email:
    *          type: string
    *        password:
    *          type: string
    *      required:
    *        - username
    *        - email
    *        - password
    */
    export default class User extends BaseModel {
    }
  • Or create a separate file containing documentation from the APIs in either TS or YAML formats, sample structure:

    project
    ├── app
    ├── config 
    ├── docs
    │   ├── controllers
    │   │   ├── **/*.ts
    │   │   ├── **/*.yml
    │   └── models
    │       ├── **/*.ts
    │       ├── **/*.yml

Best usage

  • Create files into docs/swagger, for example docs/swagger/auth.yml may contains:
/api/auth/login:
  post:
    tags:
      - Auth
    security: []
    description: Login
    parameters:
      - name: credentials
        in:  body
        required: true
        schema:
          properties:
            phone:
              type: string
              example: '1234567890'
              required: true
    produces:
      - application/json
    responses:
      200:
        description: Success
  • You can change default settings in config/swagger.ts
  • For other sample in YAML and JS format, please refer to this link.

Open http://localhost:3333/docs in your browser For detail usage, please check the Swagger specification in this SwaggerSpec

Custom UI

For using custom ui you should use own build of swagger ui. Current package contains only preconfigured and already built ui bundle. For example, you can use Adonis Edge for rendering ui with custom params.

First, install edge:

npm i @adonisjs/view

Once installed, run the following ace command to setup the package.

node ace invoke @adonisjs/view

Generate new template file using Adonis generator:

node ace make:view swagger

And then add route for custom UI:

Route.get('/', async ({ view }) => {
	const specUrl = 'your spec url'
	return view.render('swagger', { specUrl })
})

Your template should have similar content:

<!DOCTYPE html>
<head>
	<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js"></script>
	<script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
	<link rel="stylesheet" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css"/>
	<script>
		window.onload = () => {
			let ui = SwaggerUIBundle({
				url: "{{ specUrl }}",
				dom_id: "#swagger-ui",
				presets: [
					SwaggerUIBundle.presets.apis,
					SwaggerUIBundle.SwaggerUIStandalonePreset
				],
				plugins: [
					SwaggerUIBundle.plugins.DownloadUrl
				],
			})

			window.ui = ui
		}
	</script>
</head>
<body>
	<div id="swagger-ui"></div>
</body>
</html>

It is the simplest way for using custom swagger ui, but of course you could use Webpack or another bundler tool for bundling your pre configured Swagger ui.

Build swagger spec file

You can build swagger spec file the next way:

Set specFilePath option to your swagger config:

const swaggerConfig = {
	specFilePath: 'docs/swagger.json'
}

And then run adonis command:

node ace swagger:generate

Generated file will be written to by path configured in config.

Swagger modes

This package support two modes:

  • PRODUCTION
  • RUNTIME

By default RUNTIME mode enabled. When RUNTIME mode enabled package rebuild swagger spec file on each request. When you use PRODUCTION you should build your swagger spec once and then package will be respond this file content on each request.

Production using

For using swagger in production you should make some preparations:

  • Setup swagger config:
const swaggerConfig = { 
	mode: process.env.NODE_ENV === 'production' ? 'PRODUCTION' : 'RUNTIME',
	specFilePath: 'docs/swagger.json'
}
  • Add post hook for npm build script to your package.json:
{
	"scripts": {
		"build": "npm run compile",
		"postbuild": "node ace swagger:generate && cp -a docs/ build/docs"
	}
}
  • Deliver your source code to production server.

Swagger basic auth

Package supports auth via basic auth schema. For using auth you should add config in config/swagger.ts

import Env from '@ioc:Adonis/Core/Env'

export default {
	// ...Swagger congig
	swaggerAuth: {
		authMiddleware: 'swagger-auth',

		authCredentials: {
			login: Env.get('SWAGGER_AUTH_LOGIN'),
			password: Env.get('SWAGGER_AUTH_PASSWORD')
		}
	}
}

Register auth middleware in your start/kernel.ts

Server.middleware.registerNamed({
  'swagger-auth': 'Adonis/Addons/Swagger/AuthMiddleware',
})

That's all. Your swagger docs secured by basic auth.

Instead of using credentials, you can use function for verifying access in more complex way.

import Env from '@ioc:Adonis/Core/Env'
import { verifyDocsAccess } from 'App/Services/Auth/Docs'

export default {
	// ...Swagger congig
	swaggerAuth: {
		authMiddleware: 'swagger-auth',

		authCheck: async (login, password) => {
			return await verifyDocsAccess({ login, password })
		}
	}
}

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.