1.0.4 β€’ Published 23 days ago

@goodrequest/express-joi-to-swagger v1.0.4

Weekly downloads
444
License
MIT
Repository
github
Last release
23 days ago

Welcome to express-joi-to-swagger

Description

Solution that generates beatiful Swagger API documentation from code. πŸ’»

It lists all of endpoints registred within app with their routes, methods, relevant middlewares.

When it comes to generating πŸ“‘Swagger documentation, you have two options. Generate Swagger UI that can be served as a static file within your application, or keep documentation as data.json file within defined πŸ“location.

For more information see Config parameters bellow ⬇.

This simple tool does not require you to write any more code that necessary. Documentation is generated from source code itself without using annotations or separate doc files.

Installation

Use the package manager (npm or yarn) to install dependencies.

npm install @goodrequest/express-joi-to-swagger
or
yarn add @goodrequest/express-joi-to-swagger

Requirements

βœ– This solution is suitable for everybody who uses Express in a combination with Joi to build application's API. This version was developed and tested on versions 17.x.x of Joi. For version 14.x.x we have parallel branch v14. For proper functioning it is also necessary to use Typescipt version 3.7.5 and higher.

βœ– As mentioned before, it is not needed to use annotations in your code, however to make this tool works properly you need to obey some coding practices. You need define at least one router in your application. If you want to include request and response Joi schemas in a documentation they need to be named the same and exported.

βœ– If you are using middleware for user authorization and wish to include endpoint permissions in the documentation as well you need to name the function responsible for handling this and provide permissions array as its input parameter.

You can find simple examples of all mentioned in the demo folder of this repository. Quick usage example can also be found below ⬇.

Config parameters

NameTypeRequiredDescription
outputPathstringβœ…Path to directory where output JSON file should be created.
generateUIbooleanβœ…Whether Swagger UI should be generated.
permissionsobject❌Configuration parameters for parsing permissions.
permissions.parserfunction❌Custom parse function for permission middleware
permissions.middlewareNamestringβœ…Name of the middleware responsible for handling API permissions.
permissions.closurestringβœ…Name of the permission middleware closure.
permissions.paramNamestring❌Name of the parameter containing permissions passed to middleware.
permissionsFormatterfunction❌Custom formatting function for permissions description
requestSchemaNamestring❌Name of the Joi schema object defining request structure.
responseSchemaNamestring❌Name of the Joi schema object defining response structure.
requestSchemaParamsany[]❌Param for ability to pass mock params for requestSchema
responseSchemaParamsany[]❌Param for ability to pass mock params for responseSchema
errorResponseSchemaNamestring❌Name of the Joi schema object defining error responses structure.
businessLogicNamestringβœ…Name of the function responsible for handling business logic of the request.
swaggerInitInfoISwaggerInit❌Swagger initial information.
swaggerInitInfo.serversIServer[]❌List of API servers
swaggerInitInfo.servers.urlstring❌API server URL
swaggerInitInfo.infoIInfo❌Basic API information.
swaggerInitInfo.info.descriptionstring❌API description.
swaggerInitInfo.info.versionstring❌API version.
swaggerInitInfo.info.titlestring❌API title.
swaggerInitInfo.info.termsOfServicestring❌Link to terms of service.
swaggerInitInfo.info.contactIContact❌Swagger initial information.
swaggerInitInfo.info.contact.emailstringβœ…Contact email.
swaggerInitInfo.info.licenseILicense❌Swagger initial information.
swaggerInitInfo.info.license.namestringβœ…License name.
swaggerInitInfo.info.license.urlstringβœ…License url.
tagsstring❌Configuration parameters for parsing tags.
tags.baseUrlSegmentsLengthnumber❌Number of base URL segments.
tags.joinTagsboolean❌If set to true, array of parsed tags will be joined to string by tagSeparator, otherwise array of tags is returned.
tags.tagSeparatorstring❌String used to join parsed tags.
tags.versioningboolean❌If you are using multiple versions of API, you can separate endpoints also by API version. In this case it is necessary to define param "baseUrlSegmentsLength".
tags.versionSeparatorstring❌String used to separate parsed tags from API version tag is versioning == true.

Usage example

// imports
import getSwagger from '@goodrequest/express-joi-to-swagger'
import path from 'path'
import app from './your-path-to-express-app'

// Config example
const config: IConfig = {
	outputPath: path.join(__dirname, 'dist'),
	generateUI: true,
	permissions: {
		middlewareName: 'permission',
		closure: 'permissionMiddleware',
		paramName: 'allowPermissions'
	},
	requestSchemaName: 'requestSchema',
	requestSchemaParams: [mockFn],
	responseSchemaName: 'responseSchema',
	errorResponseSchemaName: 'errorResponseSchemas',
	businessLogicName: 'businessLogic',
	swaggerInitInfo: {
		info: {
			description: 'Generated Store',
			title: 'Test app'
		}
	},
	tags: {}
}

// Use case example
function workflow() {
	getSwagger(app, config).then(() => {
		console.log('DONE')
	}).catch((e) => {
		console.log('ERROR', e)
	})
}

// Start script
workflow()

Middlewares and router implementation.

router.get(
		'/users/:userID',
		
		// permissionMiddleware
		permissionMiddleware(['SUPERADMIN', 'TEST']),
		
		validationMiddleware(requestSchema),
		
		// businessLogic
		businessLogic
	)

//permissions middleware implementation
export const permissionMiddleware = (allowPermissions: string[]) => function permission(req: Request, res: Response, next: NextFunction) {
	...
}

Adding description for endpoints.

const userEndpointDesc = 'This is how to add swagger description for this endpoint'

export const requestSchema = Joi.object({
	params: Joi.object({
		userID: Joi.number()
	}),
	query: Joi.object({
		search: Joi.string().required()
	}),
	body: Joi.object({
		name: Joi.string().required()
	})
}).description(userEndpointDesc)

Top level request .alternatives() or .alternatives().try()..

export const requestSchema = Joi.object({
    params: Joi.object(),
    query: Joi.object(),
    body: Joi.alternatives().try(
        Joi.object().keys({
            a: Joi.string(),
            b: Joi.number()
        }),
        Joi.object().keys({
            c: Joi.boolean(),
            d: Joi.date()
        })
    )
})

..displays request example as:

{
  "warning": ".alternatives() object - select 1 option only",
  "option_0": {
    "a": "string",
    "b": 0
  },
  "option_1": {
    "c": true,
    "d": "2021-01-01T00:00:00.001Z"
  }
}

Marking endpoint as deprecated (by adding the @deprecated flag to the beginning of the description in the request schema).

export const requestSchema = Joi.object({
	params: Joi.object({
		userID: Joi.number()
	}),
	query: Joi.object({
		search: Joi.string().required()
	}),
	body: Joi.object({
		name: Joi.string().required()
	})
}).description('@deprecated Endpoint returns list of users.')

Using shared schema by calling .meta and specifying schema name in className property. Shared schemas can be used inside requestSchema body or anywhere in responseSchema or errorResponseSchema

export const userSchema = Joi.object({
	id: Joi.number(),
	name: Joi.string(),
	surname: Joi.string()
}).meta({ className: 'User' })

export const responseSchema = Joi.object({
	user: userSchema
})

Setting custom http status code for response (both responseSchema and errorResponseSchema) by setting it in description of schema.

export const responseSchema = Joi.object({
	id: Joi.number().integer().required()
}).description('201')

export const errorResponseSchemas = [
	Joi.object({
		messages: Joi.array().items(
			Joi.object({
				type: Joi.string().required(),
				message: Joi.string().required().example('Not found')
			})
		)
	}).description('404')
]

Result

Generated SwaggerUI

Generated SwaggerUI

Extra Benefits

Swagger bug reports shows inconsistency error in the schema and/or your route definition.

  1. In this case the default value is not present in valid values.
orderBy: Joi.string().lowercase()
.valid('name', 'duration', 'calories', 'views')
.empty(['', null]).default('order'),
  1. If you defined id as parameter within route but forgot to define it the schema Swagger will report error.
//route with id as parameter

router.put('/:id',

schema definition

//joi schema that does not include definition for id param

params: Joi.object()

Contribution

Any πŸ‘ contributions, πŸ› issues and 🌟 feature requests are welcome!

Feel free to check following #TODO ideas we have:

#IDFilenameDescription
#1@allcreate tests
#2@allupdate to new Open API after release 3.1.0 fix issue https://github.com/OAI/OpenAPI-Specification/pull/2117
#3@allsync with branch v14

Credits

1.0.4

23 days ago

1.0.3

3 months ago

1.0.2

5 months ago

1.0.1

7 months ago

1.0.0

7 months ago

0.11.1

10 months ago

0.13.0

8 months ago

0.11.2

10 months ago

0.12.0

9 months ago

0.14.0

8 months ago

0.14.1

7 months ago

0.11.0

11 months ago

0.10.2

11 months ago

0.10.1

1 year ago

0.9.0-beta

1 year ago

0.9.0

1 year ago

0.8.1

2 years ago

0.8.0

2 years ago

0.7.0

2 years ago

0.6.0

2 years ago

0.5.3

2 years ago

0.5.2

2 years ago

0.5.1

2 years ago

0.5.0

2 years ago

0.4.1

2 years ago

0.4.0

2 years ago

0.4.2

2 years ago

0.3.2

2 years ago

0.3.0

2 years ago

0.3.1

2 years ago

0.2.0

2 years ago

0.1.5

3 years ago

0.1.4

3 years ago

0.1.3

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago

0.0.16

3 years ago

0.0.15

3 years ago

0.0.14

3 years ago

0.0.13

3 years ago

0.0.12

3 years ago

0.0.11

3 years ago

0.0.10

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago