scttcper / koa2-swagger-ui Goto Github PK
View Code? Open in Web Editor NEWThis project forked from johnhof/swagger-injector
Swagger UI as Koa v2 middleware
License: MIT License
This project forked from johnhof/swagger-injector
Swagger UI as Koa v2 middleware
License: MIT License
const koaSwagger = require("koa2-swagger-ui"); // v2.12.0
console.log(koaSwagger); // { default: [Function: koaSwagger] }
It`s ok? Thx
after create an instance of koaSwagger = require('koa2-swagger-ui')
when I try to use it setting in the router router.use(koaSwagger({ swaggerOptions: { spec } }));
It's giving the error TypeError: koaSwagger is not a function
Can you add some example how do i use koa2-swagger-ui with koa-router?
I fix it manually via edit node_modules/koa2-swagger-ui/lib/index.js
return function koaSwaggerUi(ctx, next) {
if (options.routePrefix === false || ctx.path === options.routePrefix) {
ctx.type = 'text/html';
ctx.body = index(options);
return; //add return here
}
return next();
};
Whenever I try to access my /swagger
route, the aforementioned error appears in the console, and nothing will load.
I'm running all of this in typescript
.
I'm following the instructions but nothing seems to work.
// index.ts
import Koa from "koa";
import koaSwagger from "koa2-swagger-ui";
import yaml2js from "yamljs";
import appRouter from "./routes";
const app = new Koa();
const spec = yaml2js.load("swagger.yml");
appRouter.use(koaSwagger());
appRouter.get("/swagger", koaSwagger({ routePrefix: false, swaggerOptions: { spec }}));
app.use(appRouter.routes());
versions:
Hi,
How can I serve a local json or yaml file, instead of a url?
Thank you
Hi,
since version 2.11 I'm getting the following error: TypeError: Cannot read property 'swagger-ui-dist' of undefined
.
Instead of loading the library package.json
its loading our projec'ts package.json
.
I believe the cause is the use of read-pkg-up to load the package.json in this version. See file lib/index.ts
line 46:
if (!config.swaggerVersion) {
defaultOptions.swaggerVersion = readPkgUp.sync().pkg.devDependencies['swagger-ui-dist'];
}
readPkgUp
delegates on find-up
without passing any options, so find-up
uses process.cwd()
as the base search path.
As a workaround we can pass a swaggerVersion
option to koaSwagger
.
Regards.
Hi total swagger noob here. This library works great! I was up and running in seconds!
Is there any way to customize the CSS? I guess I need access to the html file rendering the JSON document somehow, but I haven't figured out how to do that...
When doing OAuth2 authentication from swagger-ui, the OAuth server will do user authorization and return the result to swagger (Koa) server's /oauth2-redirect.html
endpoint. koa2-swagger-ui
doesn't handle this endpoint, so authorization fails.
https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.20.0/
.Hello, I've just installed koa2-swagger-ui package via npm and I've updated my code with the settings on the documentation, however, for some reason, it does not load the swagger.json file.
The /docs
route opens a blank page. When I inspect the console log, it shows some error messages:
Refused to load the script 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui-bundle.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
docs:1 Refused to load the script 'https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/4.1.0/swagger-ui-standalone-preset.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
docs:71 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-CUXEv2EIcoCxm5IYzJhXO4B2nBMWti4GA5+EGW7dpG4='), or a nonce ('nonce-...') is required to enable inline execution.
I've tried to add the package to my project on both ways the documentation describes, directly to koa app and through koa-router, but both options show the same messages above.
I send below a sample of my code:
import Koa from 'koa';
import { koaSwagger } from 'koa2-swagger-ui';
import Router from 'koa-router';
let app = new Koa();
let router = new Router();
app.use(koaSwagger({
routePrefix: '/docs',
swaggerOptions: {
url: 'http://petstore.swagger.io/v2/swagger.json',
}
}));
// or
router.use(koaSwagger({
routePrefix: '/docs',
swaggerOptions: {
url: 'http://petstore.swagger.io/v2/swagger.json',
}
}));
My dependencies are:
"devDependencies": {
"@babel/core": "^7.16.12",
"@babel/eslint-parser": "^7.16.5",
"chance": "^1.1.8",
"eslint": "^8.8.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.24.2",
"eslint-plugin-import-helpers": "^1.1.0",
"eslint-plugin-jest": "^26.0.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.0.0",
"husky": "^7.0.4",
"jest": "^27.0.6",
"lint-staged": "^12.3.2",
"nock": "^13.1.3",
"nodemon": "^2.0.15",
"prettier": "^2.0.5",
"supertest": "^6.1.3"
},
"dependencies": {
"@koa/cors": "^3.1.0",
"@newrelic/winston-enricher": "^2.1.0",
"axios": "^0.25.0",
"dotenv": "^14.3.2",
"ip": "^1.1.5",
"jsonwebtoken": "^8.5.1",
"koa": "^2.13.1",
"koa-bodyparser": "^4.3.0",
"koa-helmet": "^6.1.0",
"koa-jwt": "^4.0.1",
"koa-logger": "^3.2.1",
"koa-logger-winston": "^0.0.2",
"koa-router": "^10.0.0",
"koa2-swagger-ui": "^5.3.0",
"moment": "^2.29.1",
"mssql": "^8.0.2",
"newrelic": "^8.7.0",
"sha256": "^0.2.0",
"tedious": "^14.2.0",
"tv4": "^1.3.0",
"uuid": "^8.3.2",
"winston": "^3.3.3"
}
Thank you in advance.
master
branch failed. π¨I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iβm sure you can fix this πͺ.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here are some links that can help you:
If those donβt help, or if this issue is reporting something you think isnβt right, you can always ask the humans behind semantic-release.
The npm token configured in the NPM_TOKEN
environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/
.
If you are using Two Factor Authentication for your account, set its level to "Authorization only" in your account settings. semantic-release cannot publish with the default "
Authorization and writes" level.
Please make sure to set the NPM_TOKEN
environment variable in your CI with the exact value of the npm token.
Good luck with your project β¨
Your semantic-release bot π¦π
Hi, im trying to use with multiple spec files and urls defined. but it runs only one of them if i define 2 spec.
is it possible to run like this as in swagger-ui package .
const ui = SwaggerUIBundle({
urls: [
{ name: 'v1', url: 'https://petstore.swagger.io/v2/swagger.json'},
{ name: 'v2', url: 'https://petstore.swagger.io/v2/swagger.json'}
]
})
using the middleware as its , it runs only on of them currently if i dont miss anything.
koaSwagger({
routePrefix: false,
swaggerOptions: {
urls: [
{ name: 'v1', url: 'https://petstore.swagger.io/v2/swagger.json'},
{ name: 'v2', url: 'https://petstore.swagger.io/v2/swagger.json'}
]
}
})
would be good if its possible to run with multiple endpoints as array and can version apis on UI as :
Hi,
I can't find sufficient information anywhere on the internet regarding a start-to-finish fully working example of OAuth2 using Swagger-UI. I have an OAuth2 server working and when I press the 'authenticate' button in Swagger-UI I'm redirected to the login page, I can log in, and then I am redirected back to Swagger-UI but with the URL now having an access_token value as a query param. My understanding of OAuth is that at this point the access_token should be sent with every subsequent request, but this is not happening. Is Swagger-UI even capable of this automatically? Can it parse the redirected URL and get the access_token and send it in future 'try it out' calls? Is this a manual step that a Swagger-UI user has to complete in order to bridge the gap? I'm sure if I copy and paste this access_token into an api_key security definition I could get it working, but then that amounts to two manual auth steps instead of just one...
Q&A (please complete the following information)
OS: Windows 10
Browser: Chrome
Swagger-UI version: Latest
OpenAPI version: 3.0.0
The codebase for reference:
app.use(
koaSwagger({
routePrefix: '/docs',
swaggerOptions: {
oauth2RedirectUrl:
host === 'localhost:8080'
? `http://${host}/docs`
: `https://${host}/docs`,
deepLinking: true,
spec: swagger,
},
}),
);
Swagger Code:
const {
swagger: { host },
} = require('config');
const {
dip: { url },
} = require('config');
module.exports = {
openapi: '3.0.0',
info: {
title: '',
description: 'API endpoints with request and responses',
version: '1.0.0',
},
servers: [
{
url: host === 'localhost:8080' ? `http://${host}` : `https://${host}`,
variables: {},
},
],
security: [
{
oAuth2Implicit: [
'openid',
'profile',
'email',
],
},
],
paths: {
'/products': {
get: {
tags: ['Products'],
summary: 'get all products',
description: 'Get all products',
operationId: 'GetAllProducts',
security: [],
parameters: [],
responses: {
200: {
description: 'Successful',
},
404: {
description: 'Products not found',
},
500: {
description: 'Internal server error',
},
},
deprecated: false,
},
},
'/productsForAdmin': {
get: {
tags: ['Products'],
summary: 'get all products for admin',
description: 'Get all products for admin',
operationId: 'GetAllProductsForAdmin',
security: [
{
oAuth2Implicit: [
'openid',
'profile',
'email',
],
},
],
parameters: [],
responses: {
200: {
description: 'Successful',
},
404: {
description: 'Products not found',
},
500: {
description: 'Internal server error',
},
},
deprecated: false,
},
},
},
components: {
securitySchemes: {
oAuth2Implicit: {
type: 'oauth2',
flows: {
implicit: {
authorizationUrl: `https://${url}/authorize?audience=https://api.xxxxx.xxx.com`,
tokenUrl: `https://${url}/oauth/token`,
response_type: 'token',
scopes: {
openid: '',
profile: '',
email: '',
},
},
},
},
},
schemas: {
AuthLoginRequest: {
title: 'AuthLoginRequest',
type: 'object',
properties: {
email: {
type: 'string',
},
password: {
type: 'string',
},
},
},
AuthLoginResponse: {
title: 'AuthLoginResponse',
type: 'object',
properties: {
authToken: {
type: 'string',
},
id: {
type: 'string',
},
},
},
},
},
};
Medium vulnerability has been identified by Black Duck. The faulty package is uglify-js which is a dependent package.
koa2-swagger-ui/5.7.0
handlebars/4.7.7
uglify-js/3.17.4
Reproduced on koa-swagger-ui 5.10.0.
When an OpenAPI 3 spec JSON has a response with multiple examples, UI does not render the examples correctly.
OpenAPI 3 spec JSON:
{
"paths": {
"/somepath": {
"post": {
"responses": {
"400": {
"content": {
"application/json": {
"examples": {
"invalidData": {
"statusCode": 400,
"error": "Bad Request",
"message": "Bad Request",
"errors": {
"username": [
"Username is required"
],
"password": [
"Password is required"
],
"firstName": [
"Firstname is required"
],
"lastName": [
"Lastname is required"
],
"role": [
"Role is required"
],
"enabled": [
"Enabled is required"
]
}
},
"usernameInUse": {
"statusCode": 400,
"error": "Bad Request",
"message": "Username \"someuser\" already exists"
}
}
}
}
}
}
}
}
}
}
UI renders both example values as "string" instead of the proper object structure:
my tsconfig
{
"compilerOptions": {
"module": "CommonJS",
"target": "ESNext",
"sourceMap": false,
"outDir": "./dist",
"moduleResolution": "node",
"alwaysStrict": true,
"types": [
"node"
]
},
"exclude": [
"node_modules",
"dist"
]
}
When I use import koaSwagger from "koa2-swagger-ui"
, tsc will transform my code to
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const koa2_swagger_ui_1 = require("koa2-swagger-ui");
koa2_swagger_ui_1.default({})
And it causes koa2_swagger_ui_1.default
not found error.
Maybe you should use module.exports.default
or remove module.exports
What's the preferred way of importing this module? So far I'm not able to import it so that I can use the koaSwagger function and get typings. I've tried:
import * as koaSwagger from 'koa2-swagger-ui';
results in:
TS2349: Cannot invoke an expression whose type lacks a call signature.
import koaSwagger from 'koa2-swagger-ui';
I get typings but I get the runtime error:
TypeError: koa2_swagger_ui_1.default is not a function
const koaSwagger = require('koa2-swagger-ui');
Works but I get no typings.
import { koaSwagger } from 'koa2-swagger-ui';
Cannot do this because the module has no export member named koaSwagger.
Hi,
I am using the latest version of the koa2-swagger-ui (V5.0.5) and when loading it returns the error:
swagger:84 Uncaught ReferenceError: SwaggerUIBundle is not defined at window.onload (swagger:84)
The problem is that the URL "https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/3.38.0/swagger-ui-bundle.min.js" returns a 404.
Hi, is it possible to setup Httpinterceptor for swagger?
Hi,
I am using [email protected], and everything is functioning properly. However, when I attempted to build the project using TypeScript configuration, I encountered the following error. Could you please assist me in resolving this issue?
Thanks
an UIβs css should be included in library instead of using cdn, some developers have issues with downloading that content (as they are offline / some other issues)
Hi, I'm using the module with a .yaml file and my documentation is online, but it only shows a white screen. I had to go back to V5.0.3 to be able to load my docs back again.
Hello! Thanks for creating this library, it's super helpful.
I have a question about this part:
Lines 21 to 26 in a601b85
Would it make more sense to move it to devDependencies
? Because dependencies
are transitive dependencies, which are also installed when we install koa-swagger-ui
, hence it may cause multiple copies of @types/koa
. Maybe a good reference: https://issuu.com/johan.corrales.teams.test.1/docs/effective_typescript/s/16753105
Feel free to close if this is an invalid request, or if it doesn't make sense. Thanks!
Is this up-to-date?
router.use(koaSwagger());
router.get('/docs', koaSwagger({ routePrefix: false, swaggerOptions: { spec } }));
If I change the /docs
route to anything else, /docs
will still be available. (Because of the first line, I suppose)
And will use the Default Pet Template.
what I did: (and seems to be working)
// ...
const router = new KoaRouter();
const swaggerJson = require('../../swagger.json');
router.all(['/', '/swagger', '/docs'], koaSwagger({ routePrefix: false, swaggerOptions: { spec: swaggerJson } }));
router.all('/(.*)', (ctx) => ctx.redirect('/')); // Wildcard (Not related to the issue)
// ...
import { Type } from 'class-transformer';
import { ValidateNested } from 'class-validator';
export class Test {
@Type(() => Test)
@ValidateNested()
sub: Test;
}
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
| property 'properties' -> object with constructor 'Object'
--- property 'sub' closes the circle
at JSON.stringify (<anonymous>)
at Object.<anonymous> (node_modules/koa2-swagger-ui/dist/index.js:59:57)
at Object.wrapper (node_modules/handlebars/dist/cjs/handlebars/internal/wrapHelper.js:15:19)
at Object.eval [as main] (eval at createFunctionContext (node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:262:23), <anonymous>:21:102)
at main (node_modules/handlebars/dist/cjs/handlebars/runtime.js:208:32)
at ret (node_modules/handlebars/dist/cjs/handlebars/runtime.js:212:12)
at ret (node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:519:21)
at koaSwaggerUi (node_modules/koa2-swagger-ui/dist/index.js:73:24)
at dispatch (node_modules/koa-compose/index.js:42:32)
at node_modules/koa-compose/index.js:34:12
Render 2 levels for Nested structure based on JSON.stringify()
replacer.
Our pipeline just caught a regression in the latest minor version. We're getting koaSwagger is not a function
whenever we try to initialise the middleware. I've reproduced the issue on Glitch here by installing the latest version and pasting the instructions from the Readme. If you run the server you can see the koaSwagger is not a function
errors.
It looks like there are 2 separate issues:
lib/index.js
exports the main koaSwagger
middleware with exports.default
instead of module.exports
. This means our const koaSwagger = require('koa2-swagger-ui')
now gives us an object like this instead of the function we want: { default: [Function: koaSwagger] }
index.hbs
. It looks like this is because Typescript is only copying over .ts
files in the build step. I pulled this repo and built locally and this is what my dist/
directory looks like compared to lib/
:.
βββ dist
β βββ index.d.ts
β βββ index.js
β βββ index.js.map
βββ lib
β βββ favicon-16x16.png
β βββ favicon-32x32.png
β βββ index.hbs
β βββ index.ts
I don't have any TS experience, but my brief investigation suggests that TS only supports copying across .ts
, .js
and .jsx
files, so the build process might need to include some other step for copying the other files.
By default, IE will open html generated by koa2-swagger-ui
in a IE-5
mode, which will result in below Error:
SCRIPT5009: 'SwaggerUIBundle' is undefined
And this should be fixed by adding:
<meta http-equiv="X-UA-Compatible" content="IE=edge">
in lib/index.hbs
Tried uninstalling and reinstalling, not sure if something went wrong with the release? This is the package.json from node_modules/koa2-swagger-ui, you can see it has "swagger-ui": "3.4.3"
:
{
"_from": "koa2-swagger-ui",
"_id": "[email protected]",
"_inBundle": false,
"_integrity": "sha512-Pn28tmKwTb03FIeZCRKLUGyceql+2fuXWOQqFWxRqOKur9zkf4ikX/Ud8oECsCG6wImZF9EZwrO1dxFqXRqhlA==",
"_location": "/koa2-swagger-ui",
"_phantomChildren": {
"async": "1.5.2",
"optimist": "0.6.1",
"source-map": "0.4.4",
"uglify-js": "2.8.29"
},
"_requested": {
"type": "tag",
"registry": true,
"raw": "koa2-swagger-ui",
"name": "koa2-swagger-ui",
"escapedName": "koa2-swagger-ui",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/koa2-swagger-ui/-/koa2-swagger-ui-2.6.2.tgz",
"_shasum": "f3caac43eda08e435946af57aa8e73e26eeacee1",
"_spec": "koa2-swagger-ui",
"_where": "/app",
"bugs": {
"url": "https://github.com/scttcper/koa2-swagger-ui/issues"
},
"bundleDependencies": false,
"dependencies": {
"handlebars": "^4.0.11",
"lodash.defaultsdeep": "^4.6.0"
},
"deprecated": false,
"description": "Swagger UI middleware for koa",
"devDependencies": {
"eslint": "^4.11.0",
"eslint-config-airbnb-base": "^12.1.0",
"eslint-formatter-pretty": "^1.3.0",
"eslint-plugin-import": "^2.8.0",
"koa": "^2.4.1",
"koa-router": "^7.2.1",
"mocha": "^4.0.1",
"nodemon": "^1.12.1",
"nyc": "^11.3.0",
"supertest": "^3.0.0",
"swagger-ui": "3.4.3"
},
"homepage": "https://github.com/scttcper/koa2-swagger-ui",
"keywords": [
"swagger",
"docs",
"swagger-ui",
"koa",
"koa2",
"middleware"
],
"license": "MIT",
"main": "lib/index.js",
"name": "koa2-swagger-ui",
"nyc": {
"reporter": [
"lcov",
"text"
]
},
"peerDependencies": {
"koa": "^2.4.1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/scttcper/koa2-swagger-ui.git"
},
"scripts": {
"coverage": "nyc npm test",
"lint": "eslint --format=node_modules/eslint-formatter-pretty lib test",
"start": "nodemon examples/example.js",
"test": "mocha test/*.js"
},
"version": "2.6.2"
}
There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.
Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.
Subj, it's not being called during UI init
Hello,
currently its necessary to configure requestInterceptor and also a plugin.
So I extends a local copy of your project to add the new functionality.
If you can adopt my changes to your code, I can switch back to your project.
Thx
//index.js
...
module.exports = function koaSwagger(config) {
...
// added two helper to check and render functions directly
Handlebars.registerHelper('strfnc', fnc => fnc)
Handlebars.registerHelper('isset', function (conditional, options) { return !!conditional ? options.fn(this) : options.inverse(this) })
...
master
branch failed. π¨I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iβm sure you can resolve this πͺ.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit the master
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here is some links that can help you:
If those donβt help, or if this issue is reporting something you think isnβt right, you can always ask the humans behind semantic-release.
semantic-release cannot push the version tag to the branch master
on remote Git repository.
Please refer to the authentication configuration documentation to configure the Git credentials on your CI environment.
Good luck with your project β¨
Your semantic-release bot π¦π
Hello,
with the update to 5.0.0 I receive the following error on startup when running the app in production without dev dependencies installed:
Error: Cannot find module 'lodash'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/var/app/current/node_modules/koa2-swagger-ui/dist/index.js:6:18)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
I assume this change is somehow responsible for it?
is this a bug with lodash.defaultsDeep
or an issue you can fix?
Thank you!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.