GithubHelp home page GithubHelp logo

reg2005 / adonis5-swagger Goto Github PK

View Code? Open in Web Editor NEW
104.0 104.0 7.0 2.32 MB

Swagger provider for AdonisJS 5

License: MIT License

TypeScript 77.78% HTML 19.67% JavaScript 2.55%
adonis5-swagger hacktoberfest swagger typescript

adonis5-swagger's People

Contributors

dependabot[bot] avatar rafaph avatar reg2005 avatar vladyslavparashchenko 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  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

adonis5-swagger's Issues

.yml files in docs not working on production build

Package version

[email protected]

Node.js and npm version

node --version
v12.19.0

npm --version
6.14.8

Reproduce

  1. Follow best practices to create .yml files in docs/swagger
  2. Compile for production node ace build --production
  3. Copy docs over cp docs build/docs
  4. Run production node build/server.js

Expect

Docs can also be viewed in production build

Actual

Swagger UI loaded but no specs.

Generating empty swagger spec file in github actions pipeline

Hi there,

We are not being able to generate the swagger spec file (node ace swagger:generate) during github actions workflow. The whole build happens successfully with no error message but the final spec file is empty as follow.

{"openapi":"3.0.0","info":{"title":"Project Name","version":"1.0.0","description":"Api docs"},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer"}}},"paths":{},"tags":[]}

Any help is appreciated.

Package version

    "@adonisjs/auth": "^8.0.3",
    "@adonisjs/core": "^5.1.0",
    "@adonisjs/lucid": "^14.0.2",
    "@adonisjs/mail": "^7.1.1",
    "@adonisjs/redis": "^7.0.2",
    "@adonisjs/repl": "^3.0.0",
    "@adonisjs/view": "^6.0.1",
    "@aws-sdk/client-s3": "^3.18.0",
->  "adonis5-swagger": "^1.3.3",
    "aws-sdk": "^2.906.0",
    "lodash": "^4.17.21",
    "luxon": "^1.26.0",
    "pg": "^8.6.0",
    "phc-argon2": "^1.1.1",
    "proxy-addr": "^2.0.6",
    "reflect-metadata": "^0.1.13",
    "source-map-support": "^0.5.19",
    "uuid": "^8.3.2"

Node.js and npm version

npm 6.14.10
14.17 (alpine)

Sample Code (to reproduce the issue)

We have a Dockerfile as below:

## BUILD API
FROM node:14.17-alpine as build-step
RUN mkdir /build-backend
COPY ./ /build-backend/
COPY ./.env /build-backend/.env
WORKDIR /build-backend
RUN yarn install
RUN node ace swagger:generate
RUN yarn build
RUN cp -a docs/ build/docs

## CREATE CONTAINER API
FROM node:14.17-alpine
RUN mkdir /var/backend
COPY --from=build-step /build-backend/.env /var/backend/.env
COPY --from=build-step /build-backend/build/ /var/backend/

WORKDIR /var/backend
RUN yarn install
CMD [ "node", "server.js" ]

Update

The problem (empty swagger spec file) also happens if I build and run a Docker imagem locally. Assuming Github Actions also uses containers under the hood, I'm now assuming it's impossible to generate the spec file inside a docker container. Is it right?

Swagger defaults to pet-store json file after updating to v1.4.0

Description

After updating to 1.4.0, The swagger doc use default example json file i.e. https://petstore.swagger.io/v2/swagger.json. I've to manually type in /swagger.json to navigate to my API doc.

I can confirm this works perfectly on v1.3.3 and not on v1.4.0.

Package version

1.4.0

Node.js and npm version

Node: 16.13.1
NPM: 8.1.2

Make it possible so swagger:generate command works without need to loadApp

Why this feature is required (specific use-cases will be appreciated)?

For example, when building docker image of your app... After installing dependencies it would be great to have opportunity to run node ace swagger:generate and have all the files ready up inside image itself. While building image you will not have reference to env variables like app_key and such so swagger:generate will fail. I don't see why command that generates swagger.json should boot the app before.

Have you tried any other work arounds?

No

Are you willing to work on it with little guidance?

Depends how complicated fix will be...

Unwanted redirection

Hello, i using adonisJs v5 to implement a rest api, and im using adonis5-swagger v1.4.1, and the issue that i have is whenever i try to access API_URL/docs it redirects me to another page, is there any way to prevent this redirection or to have an option to disable it, since it can be quite painful if i have a reverse proxy infront.

here is my swagger config :

export default {
	uiEnabled: true, //disable or enable swaggerUi route
	uiUrl: '/docs', // url path to swaggerUI
	specEnabled: true, //disable or enable swagger.json route
	specUrl: '/swagger.json',
	middleware: [], // middlewares array, for protect your swagger docs and spec endpoints

	options: {

		definition: {
			openapi: '3.0.0',
			info: {
				title: 'Application with swagger docs',
				version: '1.0.0',
				description: 'My application with swagger docs'
			}
		},

		apis: [
			'app/**/*.ts',
			'docs/paths/**/*.yml',
			'start/routes.ts'
		],
		basePath: '/'
	},
} as SwaggerConfig

and here is a screenshot of the redirect
image

Make the Swagger docs available when building for production

Why this feature is required (specific use-cases will be appreciated)?

When building the AdonisJS application (for production), the docs folder or the Swagger comments in the controllers/models are not included in the build folder. This then leads to the Swagger UI not showing any endpoint info when running in production.
I'm not sure if I have missed something on how to get this "out of the box" when doing a production build.

Have you tried any other work arounds?

The workaround for me has currently been to manually copy the docs folder to the build folder after the build step has completed.
Not sure if there is a workaround when adding the Swagger comments in the controllers/models? It seems like the comments get stripped out in the build step.

Are you willing to work on it with little guidance?

I currently don't have that much free time.

Error when making a POST request through Swagger.

When trying to make a POST request, the request.body() arrives empty, even though I am providing the values

Here is the configuration of my YAML file:

/tutors:
  post:
    tags:
      - Tutor
    security: []
    description: Criação de um novo tutor
    parameters:
      - name: body
        in: body
        required: true
        description: Objeto com os dados do tutor
        schema:
          type: object
          required:
            - name
            - phoneNumber1
            - email
            - password
          properties:
            name:
              type: string
              example: 'João da Silva'
              required: true
            phoneNumber1:
              type: string
              example: '(99)99999-9999'
              required: true
            phoneNumber2:
              type: string
              example: '(99)99999-9999'
              required: false
            email:
              type: string
              example: 'name@[email protected]'
              required: true
            password: 
              type: string
              example: '123456'
              required: true
    produces:
      - application/json
    responses:
      201:
        description: Cadastro realizado com sucesso
      422:
        description: Dados inválidos

Disable Validator URL?

Is there a way to disable the validatorUrl without creating a custom UI view? I'd like to disable it because all my servers are internally routed.

Package version

1.4.1

Node.js and npm version

20.2

update docs?

It took me a while to get setup as the docs lack a full example of the correct config to use

for development I had to console log through the source code to find why my config was not right, I ended up using this

// config/swagger.ts
import path from 'path';

export default {
  specEnabled: true,
  specUrl: path.resolve(__dirname, '..', 'docs', 'swagger.json'),
  specFilePath: path.resolve(__dirname, '..', 'docs', 'swagger.json'),
  uiEnabled: true,
  uiUrl: '/docs',
  options: {
    apis: ['docs/**/*.yml'],
    definition: {
      openapi: '3.0.0',
      info: {
        title: 'Hello World',
        version: '1.0.0'
      }
    }
  }
};

Cannot convert undefined or null to object

package.json:
"dependencies": {
"@adonisjs/auth": "^8.2.1",
"@adonisjs/core": "^5.8.5",
"@adonisjs/lucid": "^18.1.0",
"@adonisjs/repl": "^3.1.11",
"@adonisjs/session": "^6.4.0",
"@adonisjs/shield": "^7.0.11",
"@adonisjs/view": "^6.1.6",
"@halcyon-agile/adonis-kafka": "^0.3.3",
"adonis5-swagger": "^1.4.1",
"luxon": "^3.0.1",
"moment": "^2.29.4",
"moment-timezone": "^0.5.34",
"mysql": "^2.18.1",
"phc-argon2": "^1.1.3",
"phc-bcrypt": "^1.0.7",
"proxy-addr": "^2.0.7",
"pusher": "^5.1.1-beta",
"reflect-metadata": "^0.1.13",
"source-map-support": "^0.5.21"
}

when run command:
node ace swagger:generate

Error:

PS C:\Users\Jonathan\Desktop\Trabalho\CHATCOMPOSER-NOVO\chatcomposer-painel> node ace swagger:generate

  TypeError 

 Cannot convert undefined or null to object

 at organize C:/Users/Jonathan/Desktop/Trabalho/CHATCOMPOSER-NOVO/chatcomposer-painel/node_modules/swagger-jsdoc/src/specification.js:152
  147|      'parameters',
  148|      'definitions',
  149|      'channels',
  150|    ];
  151|    if (commonProperties.includes(property)) {
> 152|      for (const definition of Object.keys(annotation[property])) {
  153|        swaggerObject[property][definition] = mergeDeep(
  154|          swaggerObject[property][definition],
  155|          annotation[property][definition]
  156|        );
  157|      }

   1  build
     C:/Users/Jonathan/Desktop/Trabalho/CHATCOMPOSER-NOVO/chatcomposer-painel/node_modules/swagger-jsdoc/src/specification.js:316

   2  module.exports
     C:/Users/Jonathan/Desktop/Trabalho/CHATCOMPOSER-NOVO/chatcomposer-painel/node_modules/swagger-jsdoc/src/lib.js:32

   3  GenerateSwaggerFile.run
     C:/Users/Jonathan/Desktop/Trabalho/CHATCOMPOSER-NOVO/chatcomposer-painel/node_modules/adonis5-swagger/build/commands/GenerateSwaggerFile.js:20

   4  Injector.callAsync
     C:/Users/Jonathan/Desktop/Trabalho/CHATCOMPOSER-NOVO/chatcomposer-painel/node_modules/@adonisjs/fold/build/src/Ioc/Injector.js:124

Why model not appear in schemas section of swagger?

Why model not appear in schemas section of swagger?

Package version

adonis5-swagger: ^1.3.3

Node.js and npm version

node: 16
npm: 8.3.2

Sample Code (to reproduce the issue)

/** 
  *  @swagger
  *  definitions:
  *    User:
  *      type: object
  *      properties:
  *        name: 
  *          type: string
  *        email:
  *          type: string
  * /
  

Authorize button on ui

Why the authorization button not showing on ui? any good example?

swagger.json

{
  "openapi":"3.0.0",
  "info":{
    "title":"Simbyo Api",
    "version":"1.0.0",
    "description":"XX!"
  },
  "paths":{},
  "components":{
    "securitySchemes":{
      "bearerAuth":{
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  },
  "tags":[]
}

auth.yml

/api/auth/logout:
  post:
    summary: Logout
    security:
      - bearerAuth: []
    responses:
      200:
        description: Success
      422:
        description: Failed
      401:
        description: Unauthorized

this.container.use is not a function

Package version

Adonis Core Version: 5.1.4
Adonis5 Swagger Version: 1.2.1

Node.js and npm version

Node Version: 14.15.3
NPM Version: 6.14.9
Yarn Version: 1.22.10

Sample Code (to reproduce the issue)

Update adonis to the latest version

BONUS (a sample repo to reproduce the issue)

Just any newly created adonis App

TypeError: this.container.use is not a function


1 SwaggerProvider.initSwaggerRoutes
  /Users/devonte/Documents/GetCircuit/circuit-engine/node_modules/adonis5-swagger/build/providers/SwaggerProvider.js:14

2 SwaggerProvider.boot
  /Users/devonte/Documents/GetCircuit/circuit-engine/node_modules/adonis5-swagger/build/providers/SwaggerProvider.js:10

3 Registrar.boot
  /Users/devonte/Documents/GetCircuit/circuit-engine/node_modules/@adonisjs/fold/build/src/Registrar/index.js:116

4 anonymous
  /Users/devonte/Documents/GetCircuit/circuit-engine/node_modules/@adonisjs/application/build/src/Application.js:543

5 Profiler.profileAsync
  /Users/devonte/Documents/GetCircuit/circuit-engine/node_modules/@adonisjs/profiler/build/src/Profiler/AbstractProfiler.js:20

6 Application.bootProviders
  /Users/devonte/Documents/GetCircuit/circuit-engine/node_modules/@adonisjs/application/build/src/Application.js:541

7 HttpServer.wire
  /Users/devonte/Documents/GetCircuit/circuit-engine/node_modules/@adonisjs/core/build/src/Ignitor/HttpServer/index.js:56

8 HttpServer.start
  /Users/devonte/Documents/GetCircuit/circuit-engine/node_modules/@adonisjs/core/build/src/Ignitor/HttpServer/index.js:146

Running `node ace swagger:generate` fails without app env variables

Prerequisites

Running node ace swagger:generate fails without env variables. The case where we build it in the ci/cd, it's not good to put the app envs there. Furthermore, the node ace build itself can be run successfully without the env variables.

image

Package version

1.4.1

Node.js and npm version

❯ node -v
v16.19.1

❯ npm -v
8.19.3

Sample Code (to reproduce the issue)

BONUS (a sample repo to reproduce the issue)

Cannot read properties of undefined (reading 'replace')

Package version

1.4.1

Node.js and npm version

v20.9.0 / v10.2.3

Sample Code (to reproduce the issue)

Hello,

I'm trying to install swagger in my project but I got stuck, I don't know if I did something wrong or there is a real problem

I did :

npm install --save adonis5-swagger
node ace invoke adonis5-swagger
node ace serve

It modified my .adonisrc.json

"commands": [
        "...",
        "adonis5-swagger/build/commands"
    ],
    "providers": [
        "...",
        "adonis5-swagger"
    ],

And then I got :

> node ace serve --watch

[ info ]  building project...
[ info ]  starting http server...

   TypeError: Cannot read properties of undefined (reading 'replace')


   ⁃ dropSlash
     /Users/teo/dev/troubadour/api-troubadour/node_modules/@adonisjs/http-server/build/src/helpers.js:31
   ⁃ Route.computePattern
     /Users/teo/dev/troubadour/api-troubadour/node_modules/@adonisjs/http-server/build/src/Router/Route.js:79
   ⁃ Route.toJSON
     /Users/teo/dev/troubadour/api-troubadour/node_modules/@adonisjs/http-server/build/src/Router/Route.js:190

If anyone got an idea about why this happen
Thanks in advance !

Running in Heroku (Empty swagger.json)

I stood up a starter Adonis5 application (API) and I'm trying to get it to run in production on Heroku. As a temporary workaround, I hard coded mode: 'RUNTIME' inside of swagger.ts. This seemed to work fine and I could see my one controller's docs just fine. Of course, I have since put this back.

First, I ran into this issue: #41

  • Commenting out PORT and APP_NAME worked for me (in env.ts).

Then, I ran into this issue: #33

  • Creating a /docs folder with a /docs/.keep finally made the build successful.

However, now my docs have all disappeared. The swagger page shows this error: No operations defined in spec! and my swagger.json file appears to have been built like this:

{"openapi":"3.0.0","info":{"title":"My Adonis5 App","version":"1.0.0"},"paths":{},"components":{},"tags":[]}

I checked the server and both files were built this way...the one in /docs/swagger.json and then the one that got copied to /build/docs/swagger.json.

As per the instructions (https://github.com/reg2005/adonis5-swagger#production-using) my package.json file has the postbuild script:

"build"     : "node ace build --production",
"postbuild" : "node ace swagger:generate && cp -a docs/ build/docs",

My versions:

adonis5-swagger : 1.4.1
node : 20.2.0

If I run node ace swagger:generate locally, it creates the proper /docs/swagger.json file. Any idea why it's empty in production?

node ace `serve` and `invoke` are not a registered command

Package version

"@adonisjs/ace": "^5.0.8",
"adonis5-swagger": "^1.2.1"

Node.js and npm version

node: v14.7.0
npm: 6.14.7

Sample Code (to reproduce the issue)

node ace serve --watch
node ace invoke adonis5-swagger

The command serve and invoke are not recognized by ace.
Is this related to this package ?

Not Found /swagger.json

Hello, my problem rises when a try to deploy the api to render, when i visit the /docs
i get Fetch error Not Found /swagger.json.
I follow the readme.md but i don't know what else to do.

Package version

"adonis5-swagger": "^1.4.1"

Node.js and npm version

16

Sample Code (to reproduce the issue)

export default {
uiEnabled: true, //disable or enable swaggerUi route
uiUrl: 'docs', // url path to swaggerUI
specEnabled: true, //disable or enable swagger.json route
specUrl: '/swagger.json',

middleware: [], // middlewares array, for protect your swagger docs and spec endpoints

Stream error on loading swagger doc page

Package version

1.4.1

Node.js and npm version

Node: v16.16.0 & npm: 8.16.0

Sample Code (to reproduce the issue)

I'd version v1.4.0 installed earlier and it was working fine until today when I upgraded it to the latest i.e. v1.4.1. On loading the swagger doc page I'm getting this error.

Endpoint: http://localhost:3333/docs/index.html

{"fd":null,"path":"/Users/istiyaktailor/Documents/Projects/credilio-api/node_modules/swagger-ui-dist/index.html","flags":"r","mode":438,"end":null,"bytesRead":0,"closed":false,"_readableState":{"objectMode":false,"highWaterMark":65536,"buffer":{"head":null,"tail":null,"length":0},"length":0,"pipes":[],"flowing":null,"ended":false,"endEmitted":false,"reading":false,"constructed":false,"sync":true,"needReadable":false,"emittedReadable":false,"readableListening":false,"resumeScheduled":false,"errorEmitted":false,"emitClose":true,"autoDestroy":true,"destroyed":false,"errored":null,"closed":false,"closeEmitted":false,"defaultEncoding":"utf8","awaitDrainWriters":null,"multiAwaitDrain":false,"readingMore":false,"dataEmitted":false,"decoder":null,"encoding":null,"object_mode":false,"high_water_mark":65536,"end_emitted":false,"need_readable":false,"emitted_readable":false,"readable_listening":false,"resume_scheduled":false,"error_emitted":false,"emit_close":true,"auto_destroy":true,"close_emitted":false,"default_encoding":"utf8","await_drain_writers":null,"multi_await_drain":false,"reading_more":false,"data_emitted":false},"_events":{},"_eventsCount":1,"bytes_read":0,"readable_state":{"objectMode":false,"highWaterMark":65536,"buffer":{"head":null,"tail":null,"length":0},"length":0,"pipes":[],"flowing":null,"ended":false,"endEmitted":false,"reading":false,"constructed":false,"sync":true,"needReadable":false,"emittedReadable":false,"readableListening":false,"resumeScheduled":false,"errorEmitted":false,"emitClose":true,"autoDestroy":true,"destroyed":false,"errored":null,"closed":false,"closeEmitted":false,"defaultEncoding":"utf8","awaitDrainWriters":null,"multiAwaitDrain":false,"readingMore":false,"dataEmitted":false,"decoder":null,"encoding":null,"object_mode":false,"high_water_mark":65536,"end_emitted":false,"need_readable":false,"emitted_readable":false,"readable_listening":false,"resume_scheduled":false,"error_emitted":false,"emit_close":true,"auto_destroy":true,"close_emitted":false,"default_encoding":"utf8","await_drain_writers":null,"multi_await_drain":false,"reading_more":false,"data_emitted":false},"events":{},"events_count":1}

I debugged the code and noticed that in v1.4.1 we are sending the html file i.e. index.html as stream.

return response.header('Content-Type', contentType).stream(fs.createReadStream(path))

While, in v1.4.0 we read the html file and then send it in response.

let data = await fsp.readFile(path, 'utf-8')
if (fileName.includes('index.html')) {
//replace default host from index.html
data = data.replace(
'https://petstore.swagger.io/v2/swagger.json',
this.config.get('swagger.specUrl')
)
}
return response.header('Content-Type', contentType).send(data)

I could confirm that reading the file first using fs.readFileSync and then sending it in response via response.send(file) fixes the issue.

adonis5-swagger SwaggerConfig don't working. Plase, change to my working config.

This your config don't wokring
export default {
// ... config options
options: {
definition: {
openapi: '3.0.0',
info: {
title: 'Application with swagger docs',
version: '1.0.0',
description: 'My application with swagger docs'
},
components: {
securitySchemes: {
bearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT"
}
}
}
}
//... config options
}
} as SwaggerConfig

This my config wokring

export default { // ... config options options: { definition: { openapi: '3.0.0', info: { title: 'Application with swagger docs', version: '1.0.0', description: 'My application with swagger docs' }, components: { securitySchemes: { bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" } } } } //... config options } } as SwaggerConfig

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.