Skip to content

Instantly share code, notes, and snippets.

@ChaseIngebritson
Last active May 18, 2021 22:18
Show Gist options
  • Save ChaseIngebritson/877ab00c878a76e34c812bdaba0ca831 to your computer and use it in GitHub Desktop.
Save ChaseIngebritson/877ab00c878a76e34c812bdaba0ca831 to your computer and use it in GitHub Desktop.
Serverless Express Swagger JSDocs
Add documentation to a serverless Express API using JSDoc.
import swaggerJsdoc from 'swagger-jsdoc'
import writeJsonFile from 'write-json-file'
import definition from '../src/docs/swaggerDef'
const options = {
definition,
apis: ['src/docs/*.yml', 'src/routes/v1/*.js']
};
const openapiSpecification = swaggerJsdoc(options);
writeJsonFile('src/docs/swagger.json', openapiSpecification);
version: 0.1
phases:
install:
commands:
- echo "Installing dependencies..."
- npm ci
- npx serverless plugin install
--name serverless-webpack
pre_build:
commands:
build:
commands:
- echo "Building..."
- npm run build-docs
- npm run build
post_build:
commands:
- echo "Syncing files to S3..."
- aws s3 sync ./.serverless "s3://bucket"
--delete
components:
schemas:
NumClients:
type: object
properties:
clients:
type: number
example:
clients: 1423
Error:
type: object
properties:
code:
type: number
message:
type: string
responses:
NotFound:
description: Not found
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
example:
code: 404
message: Not found
import HTTPStatus from 'http-status';
import specs from '../docs/swagger.json'
export async function getDocs(req, res, next) {
try {
return res.status(HTTPStatus.OK).json(specs);
} catch (err) {
err.status = HTTPStatus.BAD_REQUEST;
return next(err);
}
}
{
"paths": {},
"components": {
"schemas": {
"NumClients": {
"type": "object",
"properties": {
"clients": {
"type": "number"
}
},
"example": {
"clients": 1423
}
},
"Error": {
"type": "object",
"properties": {
"code": {
"type": "number"
},
"message": {
"type": "string"
}
}
}
},
"responses": {
"NotFound": {
"description": "Not found",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
},
"example": {
"code": 404,
"message": "Not found"
}
}
}
}
}
},
"tags": []
}
import { version, description } from '../../package.json'
const swaggerDef = {
openapi: '3.0.0',
info: {
title: 'Example',
version,
description,
}
};
export default swaggerDef
/**
* Test Routes
*/
import { Router } from 'express';
import * as TestController from '../../controllers/test.controller';
const routes = new Router();
/**
* CRUD
*/
routes.get('/db', TestController.getDb);
export default routes;
/**
* @swagger
* tags:
* name: Test
* description: Test endpoint for docs
*/
/**
* @swagger
* /test:
* get:
* summary: Get test
* description: Get information on the database as a test case for the docs
* tags: [Test]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment