Code Monkey home page Code Monkey logo

nestjs-redoc's Introduction

NestJS-Redoc

ReDoc powered frontend for your NestJS API spec

๐Ÿ“’ This is a ReDoc powered frontend for your NestJS API spec.

โšก Features

  • Customizable theme
  • It's almost a drop in replacement for you current swagger UI, you only need to import this package and modify any settings you may want to change (e.g: Page title, ReDoc options)

๐Ÿ—ฟ Installation

Using npm: npm i nestjs-redoc

Using yarn: yarn add nestjs-redoc

โ“ How to use

You need to install the Swagger Module first if you want to get definitions updated with your project.

In future versions you will be able to pass a URL parameter as document, but for the moment you need this document object from the swagger module

const options = new DocumentBuilder()
  .setTitle('Look, i have a title')
  .setDescription('A very nice description')
  .setBasePath('/api/v1')
  .build();
const document = SwaggerModule.createDocument(app, options);

Then add the following example code.

Note: All properties are optional, if you don't specify a title we will fallback to the one you used in your DocumentBuilder instance.

const redocOptions: RedocOptions = {
  title: 'Hello Nest',
  logo: {
    url: 'https://redocly.github.io/redoc/petstore-logo.png',
    backgroundColor: '#F0F0F0',
    altText: 'PetStore logo'
  },
  sortPropsAlphabetically: true,
  hideDownloadButton: false,
  hideHostname: false,
  auth: {
    enabled: true,
    user: 'admin',
    password: '123'
  },
  tagGroups: [
    {
      name: 'Core resources',
      tags: ['cats'],
    },
  ],
};
// Instead of using SwaggerModule.setup() you call this module
await RedocModule.setup('/docs', app, document, redocOptions);

Available options

Redoc Options

Option Description Type Note
title Web site title (e.g: ReDoc documentation) string
favicon Web site favicon URL string Fallbacks to the document title if not set
logo Logo options LogoOptions See LogoOptions table
theme Theme options ThemeOptions See ThemeOptions info
untrustedSpec If set, the spec is considered untrusted and all HTML/markdown is sanitized to prevent XSS, by default is false boolean
supressWarnings If set, warnings are not rendered at the top of documentation (they are still logged to the console) boolean
hideHostname If set, the protocol and hostname won't be shown in the operation definition boolean
expandResponses Specify which responses to expand by default by response codes, values should be passed as comma-separated list without spaces (e.g: 200, 201, "all") string
requiredPropsFirst If set, show required properties first ordered in the same order as in required array boolean
sortPropsAlphabetically If set, propeties will be sorted alphabetically boolean
showExtensions If set the fields starting with "x-" will be shown, can be a boolean or a string with names of extensions to display boolean
noAutoAuth If set, redoc won't inject authentication section automatically boolean
pathInMiddlePanel If set, path link and HTTP verb will be shown in the middle panel instead of the right one boolean
hideLoading If set, loading spinner animation won't be shown boolean
nativeScrollbars If set, a native scrollbar will be used instead of perfect-scroll, this can improve performance of the frontend for big specs boolean
hideDownloadButton This will hide the "Download spec" button, it only hides the button boolean
disableSearch If set, the search bar will be disabled boolean
onlyRequiredInSamples Shows only required fileds in request samples boolean
auth Auth options AuthOptions See AuthOptions info
AuthOptions info
enabled If enabled, a prompt will pop out asking for authentication details, default: false boolean
user User name, default: admin string
password User password, default: 123 string
tagGroups Tag groups options TagGroupOptions[] See Tag Group options
Tag Group options info
name Tag name string
tags Tag collection string[]
redocVersion Set an specific redoc version string,number By default it's "latest"

Note: If you want to change your ReDoc theme settings, take a look at the official ReDoc documentation: https://github.com/Redocly/redoc/blob/master/src/theme.ts

Apply the properties defined in ResolvedThemeInterface to the key called "theme" in the redoc options

Logo options

Option Description Type Example
url The URL pointing to the spec Logo, must be in the format of a URL and an absolute URL string
backgroundColor Background color to be used, must be RGB color in hexadecimal format (e.g: #008080) string #F0F0F0
altText Alt tag for Logo string PetStore
href href tag for Logo, it defaults to the host used for your API spec string

๐Ÿ‘จโ€๐Ÿ’ป๐Ÿ‘ฉโ€๐Ÿ’ป Contributors

  • Special thanks to Jay McDoniel (jmcdo29) who helped with code refactoring and unit tests! ๐Ÿ‘
  • @joemaidman

๐Ÿ“œ Changelog

Bellow are a list of changes, some might go undocumented

  • 1.0.0 - First release
  • 1.1.0 - Minor changes, nothing too important
  • 1.2.0 - Added unit tests, refactored code
  • 1.2.1 - Updated to work with the latest version of nest swagger module
  • 1.2.2 - Fixed issue with URL on windows
  • 1.3.0 - Added favicon option (by @joemaidman)
  • 2.0.0 - Added authentication option, fixed issues with CSP and nestjs version compatibility issues
  • 2.1.0 - Added x-tagGroups extension property
  • 2.1.1 - Fixed CSP issue on Safari browser
  • 2.2.0 - Added version property, this way you can pin redoc to a specific version
  • 2.2.2 - Updated to support Nest 8

๐Ÿ“‹ ToDo

  • Add Fastify support
  • Add the option to use a spec URL instead of document
  • Fix tests

nestjs-redoc's People

Contributors

antongolub avatar dependabot[bot] avatar jmcdo29 avatar lembdev avatar ojoanalogo avatar pismenskiy avatar ulrichfrancomme 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  avatar  avatar

nestjs-redoc's Issues

Update to NestJS 9

The interface INestApplication changed the name 'listenAsync' method to 'listen'.

New library supporting NestJS 10, ExpressJS & Fastify, multi-user basic auth and more

Hi,

because this repository is not maintained for over 3 years and other alternatives are either part of a framework (that I don't need) or just slightly updated versions of this package, I decided to create a library myself:

nestjs-redox

Features:

  • NestJS 10 support
  • ExpressJS and Fastify support
  • Multi-user auth basic support
  • Option "standalone" for self hosted redoc bundles
  • Option to disable Google fonts

I hope this library helps all devs who are looking for an alive and most updated solution for using Redoc in their NestJS projects ๐Ÿš€

Cannot run the 'app' in RedocModule.setup();

Hello Redoc, thank you for your awesome work. But i have a bit issue on how to install it.

So, I have already done all the installation and put some code inside my main.ts file exactly the same:

const options = new DocumentBuilder()
  .setTitle('Look, i have a title')
  .setDescription('A very nice description')
  .setBasePath('/api/v1')
  .build();
  const document = SwaggerModule.createDocument(app, options);

  const redocOptions: RedocOptions = {
    title: 'Hello Nest',
    logo: {
      url: 'https://redocly.github.io/redoc/petstore-logo.png',
      backgroundColor: '#F0F0F0',
      altText: 'PetStore logo'
    },
    sortPropsAlphabetically: true,
    hideDownloadButton: false,
    hideHostname: false
  };
  // Instead of using SwaggerModule.setup() you call this module
  await RedocModule.setup('/docs', app, document, redocOptions);

Focused on the line code : await RedocModule.setup('/docs', app, document, redocOptions);

I have an issue on 'app' such as:

Argument of type 'import("/Users/kcb/Documents/Projects/Sample/Deploy_zeit/deploy-zeit/node_modules/@nestjs/common/interfaces/nest-application.interface").INestApplication' is not assignable to parameter of type 'import("/Users/kcb/Documents/Projects/Sample/Deploy_zeit/deploy-zeit/node_modules/nestjs-redoc/node_modules/@nestjs/common/interfaces/nest-application.interface").INestApplication'.
  The types returned by 'getHttpAdapter().createMiddlewareFactory(...)' are incompatible between these types.

Perhaps, you guys can help me on this issue. Thanks!

Sync redoc options

redoc is adding sortTagsAlphabetically and some other options, but cannot bypass nestjs-redoc validator

Question: How to add custom tags with custom description?

In the image in the readme file I see tags like Introduction, Authentication and so on. How can those be added?

For example, I need an Introduction tag explaining high level the functionality. How can this be done?

Thank you ๐Ÿ˜Š

swagger.json not secured

When I'm protect my documentation with

    auth: {
      enabled: true,
      user: config.get('openapi.user'),
      password: config.get('openapi.password'),
    },

this works for main page, but doesn't protect access to swagger.json!!!

See related
#19 (comment)

Some features on the page are very slow

Since yesterday, the speed is very slow or stopped when expanding the response type or scrolling.

Looking at the page script, src="https://cdn.jsdelivr.net/npm/redoc@latest/bundles/redoc.standalone.js" is used as the script, which is presumed to be a side effect created by using the latest version.

Can you specify the version like this?

<script src="https://cdn.jsdelivr.net/npm/[email protected]/bundles/redoc.standalone.js"> </script>

the sources:
Redocly/redoc#1883

"Patch" version bump should have been major

The patch version bump from 1.3.0 to 1.3.1 contained some major dependency updates and probably should have been a 2.0.0.

Specifically the Nest version here changes the INestApplication type.

This broke my app with the following:

src/documentation/documentation.service.ts:44:39 - error TS2345: Argument of type 'import("/app/node_modules/@nestjs/common/interfaces/nest-application.interface").INestApplication' is not assignable to parameter of type 'import("/app/node_modules/nestjs-redoc/node_modules/@nestjs/common/interfaces/nest-application.interface").INestApplication'.
  Property 'registerRequestByContextId' is missing in type 'import("/app/node_modules/@nestjs/common/interfaces/nest-application.interface").INestApplication' but required in type 'import("/app/node_modules/nestjs-redoc/node_modules/@nestjs/common/interfaces/nest-application.interface").INestApplication'.

Can we revert this and do it again as a major version change? For the moment I pinned to 1.3.0.

Add tests to the project

Creating an issue for better tracking, I'm working on adding tests to the package for 100% (or as close as I can get) coverage! ๐ŸŒŸ

TypeError: Cannot read property 'enabled' of undefined

NestJS server fails with error when redoc options doesn't have 'auth' optional parameter because of the line 135 of redoc-module.ts below.

if (options.auth.enabled) { const { user, password } = options.auth; expressAuth({ users: { [user]: password }, challenge: true })( req, res, () => { sendPage(); } ); } else { sendPage(); }

Also, I'm not sure if it makes sense to have auth optional option, but user & password required. What if enabled is false?

auth?: { enabled: boolean; user: string; password: string; };

Cant load swagger file in Nest app running with url prefix

We should load swagger from relative url because nest application could be proxied with some path prefix by some server like NGINX behind.

For example, we have Nest app with simple /docs/ route. And some SPA application on same domain. We will configure NGINX like

location /api {
   // upstream to Nest app
}

location {
 // route everything didnt match /api prefix to static files
}

In these cause a broken link swagger.json because it will be generated from the root

And these why all static files are loaded in original SwaggerModule

<script src="./swagger-ui-bundle.js"> </script>
<script src="./swagger-ui-standalone-preset.js"> </script>
<script src="./swagger-ui-init.js"> </script>

NestJS v7 issue

I'm using NestJS 7.5.1.

  "dependencies": {
    "@nestjs/common": "^7.5.1",
    "@nestjs/core": "^7.5.1",
    "@nestjs/platform-express": "^7.5.1",
    "@nestjs/swagger": "^4.6.1",
    "nestjs-redoc": "^1.3.2",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^6.6.3",
    "swagger-ui-express": "^4.1.4"
  },

And I got this error.

src/main.ts:39:36 - error TS2345: Argument of type 'import("/home/erickalmeida/dev/generic-adapter-nest/node_modules/@nestjs/common/interfaces/nest-application.interface").INestApplication' is not assignable to parameter of type 'import("/home/erickalmeida/dev/generic-adapter-nest/node_modules/nestjs-redoc/node_modules/@nestjs/common/interfaces/nest-application.interface").INestApplication'.
  The types returned by 'getHttpAdapter().createMiddlewareFactory(...)' are incompatible between these types.
    Type '((path: string, callback: Function) => any) | Promise<(path: string, callback: Function) => any>' is not assignable to type '(path: string, callback: Function) => any'.
      Type 'Promise<(path: string, callback: Function) => any>' is not assignable to type '(path: string, callback: Function) => any'.
        Type 'Promise<(path: string, callback: Function) => any>' provides no match for the signature '(path: string, callback: Function): any'.

39 await RedocModule.setup('/docs', app, document, redocOptions);

multiple security

Hello! How can i use multiple security with AND condition, not OR

image

Incompatibility with Nest MVC techniques

nestjs-redoc rewrites views directory base path and templates engine of the application, ruining Nest MVC techniques:
https://docs.nestjs.com/techniques/mvc#model-view-controller

Nest:

app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('hbs');

nestjs-redoc (https://github.com/mxarc/nestjs-redoc/blob/master/src/redoc-module.ts#L97):

// Set app to use handlebars as engine
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
// Set views folder
app.set('views', join(__dirname, '..', 'views'));

Because of this, it is not possible to use nestjs-redoc and render project own pages at the same time.

Maintained

Is this project still being maintained?

Custom fonts or specify html template

Your docs outline how to modify the the theme and it all works as intended however I can't see any method to add custom fonts to the html template to then set in the theme config.

The official Redoc files reference settings a htmlTemplate but this key is outside the theme key and so can't be configured with the nestjs-redoc options

How to secure docs route?

I want to restrict access to /docs route from not logged in users. Maybe someone has an example for this? :)

Could not run redoc in local project - sandbox is empty

Hi , first of all thank you for a nice repo

I trying to implemnt in my project and I got page with lot of errors, i cant add data . the sandbox is empty ..etc

my code
controller :

 @ApiOperation({ title: 'create a token' })
  @ApiImplicitHeader({ name: 'Autherization' })
  @UseGuards(AuthGuard)
  @Get('token')
  @ApiResponse({ status: 201, description: 'The record has been successfully created.'})
  @ApiResponse({ status: 403, description: 'Forbidden.'})
  public async getToken(@Request() request: TokenRequest) {
    try {
      return this.authService.createToken(request.credentials);
    } catch (e) {
      throw new UnauthorizedException();
    }
  }

main.ts

const options = new DocumentBuilder()
  .setTitle('app title')
  .setDescription('apii')
  .setVersion('1.0')
  .build();

const redocOptions: RedocOptions = {
    title: 'Hello Nest',
    logo: {
      url: 'https://redocly.github.io/redoc/petstore-logo.png',
      backgroundColor: '#F0F0F0',
      altText: 'PetStore logo'
    },
    sortPropsAlphabetically: true,
    hideDownloadButton: false,
    hideHostname: false
  };

const document = SwaggerModule.createDocument(app, options);
//SwaggerModule.setup('api', app, document);
await RedocModule.setup('/docs', app, document, redocOptions);  

example does not work in ApiHeader

@ApiHeader({ name: 'Authorization', example: 'Bearer 2YotnFZFEjr1zCsicMWpAA', description: 'description' })
This gives the following result. The description field is also not clearly displayed at all

image

I would also like to know how to change the default api name of the route AccountConsentsController_createAccountConsents

image

TagGroups `namespaces`

It would be nice to add namespaces at the group level, like this:

tagGroups:
      - name: 'User'
        tags:
          - 'Entity'
          - 'Reports'
      - name: 'Common'
        tags:
          - 'Reports'

And in decorators:

@ApiTags('User.Reports')
// ... some user reports controller

@ApiTags('Common.Reports')
// ... some common reports controller

But render without dots, like:

User
> Reports

Common
> Reports

Use of Redoc Vendor Extensions

Hello,

Thank you for your plugin, this is really useful !

I was trying to use a redoc vendor extension, the x-tagGroups,
but I don't know how to do it.

Is there a way ? Or do we have to write some code in your plugin to make this work ?

Thanks !

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.