08 Documentation - jp7io/typescript-crud-api GitHub Wiki
Documentation
Add Swagger
yarn add swagger-ui-express js-yaml
yarn add @types/swagger-ui-express @types/js-yaml --dev
Create route for docs
code ./src/routes/docs.ts
import { Router } from 'express';
import swaggerUi, { JsonObject } from 'swagger-ui-express';
import yaml from 'js-yaml';
import path from 'path';
import fs from 'fs';
export const docsRoutes = (router: Router) => {
const fileContents = fs.readFileSync(
path.resolve(__dirname, '../../swagger.yaml'),
'utf8'
);
const swaggerDocument = yaml.load(fileContents) as JsonObject;
if (process.env.APP_URL) {
swaggerDocument.host = process.env.APP_URL.replace(/https?:\/\//, '');
if (process.env.APP_URL.includes('https://')) {
swaggerDocument.schemes = ['https'];
}
}
const swagger = swaggerUi.setup(swaggerDocument, {
customSiteTitle: 'TypeScript CRUD API',
});
router.use(swaggerUi.serve);
router.get('/', swagger);
return router;
};
Add the route into the app
code ./src/app.ts
...
import { docsRoutes } from './routes/docs';
export const app = async (port: number) => {
...
app.use(authorsRoutes(router));
app.use(docsRoutes(router));
...
};
YAML
code ./swagger.yaml
swagger: '2.0'
info:
title: TypeScript CRUD API (Backend)
description: https://github.com/jp7internet/typescript-crud-api
host: localhost:4000
schemes:
- http
paths:
/articles:
get:
tags: [articles]
parameters:
- name: relations[]
in: query
description: 'Which relations should be returned (e.g.: author)'
responses:
200:
description: OK
post:
tags: [articles]
parameters:
- name: body
in: body
responses:
200:
description: OK
schema:
$ref: '#/definitions/ARTICLE'
/articles/{id}:
get:
tags: [articles]
parameters:
- name: id
in: path
responses:
200:
description: OK
put:
tags: [articles]
parameters:
- name: id
in: path
- name: body
in: body
responses:
200:
description: OK
schema:
$ref: '#/definitions/ARTICLE'
delete:
tags: [articles]
parameters:
- name: id
in: path
responses:
200:
description: OK
/authors:
get:
tags: [authors]
parameters:
- name: relations[]
in: query
description: 'Which relations should be returned (e.g.: articles)'
responses:
200:
description: OK
post:
tags: [authors]
parameters:
- name: body
in: body
responses:
200:
description: OK
schema:
$ref: '#/definitions/ARTICLE'
/authors/{id}:
get:
tags: [authors]
parameters:
- name: id
in: path
responses:
200:
description: OK
put:
tags: [authors]
parameters:
- name: id
in: path
- name: body
in: body
responses:
200:
description: OK
schema:
$ref: '#/definitions/ARTICLE'
delete:
tags: [authors]
parameters:
- name: id
in: path
responses:
200:
description: OK
definitions:
ARTICLE:
type: object
properties:
title:
type: string
text:
type: string
author:
type: number
AUTHOR:
type: object
properties:
name:
type: string
Open documentation in the browser
yarn dev
open http://localhost:4000
Add Documentation to Git
git add .
git commit -m "Documentation"