-
Notifications
You must be signed in to change notification settings - Fork 7
/
SwaggerController.ts
60 lines (55 loc) · 2.11 KB
/
SwaggerController.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { IocContract } from '@adonisjs/fold/build'
import { ConfigContract } from '@ioc:Adonis/Core/Config'
import mime from 'mime'
import buildJsDocConfig from './Utils/buildJsDocConfig'
import swaggerJSDoc from 'swagger-jsdoc'
import * as fs from 'fs'
import { promises as fsp } from 'fs'
import { Application } from '@adonisjs/application'
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { join } from 'path'
import { ReadStream } from 'fs'
export class SwaggerController {
private config: ConfigContract
private app: Application
constructor(protected IoC: IocContract) {
this.config = IoC.use('Adonis/Core/Config')
this.app = this.IoC.use('Adonis/Core/Application')
}
public async swaggerUI({ params, response }: HttpContextContract) {
const swaggerUiAssetPath =
this.config.get('swagger.swaggerUiDistPath') || require('swagger-ui-dist').getAbsoluteFSPath()
if (!params.fileName) {
const baseUrl = this.config.get('swagger.uiUrl', '/docs').replace('/', '')
return response.redirect(`/${baseUrl}/index.html`)
}
let fileName = params.fileName ? params.fileName : 'index.html'
const path = join(swaggerUiAssetPath, fileName)
const contentType = mime.getType(path)
let data = await fsp.readFile(path, 'utf-8')
if (fileName.includes('index.html')) {
//replace default host from index.html
data = data.replace(
'https://petstore.swagger.io/v2/swagger.json',
this.config.get('swagger.specUrl')
)
}
return response.header('Content-Type', contentType).send(data)
}
public async swaggerFile({ response }: HttpContextContract): Promise<void> {
const mode = this.config.get('swagger.mode', 'RUNTIME')
if (mode === 'RUNTIME') {
response.send(swaggerJSDoc(buildJsDocConfig(this.config.get('swagger.options', {}))))
} else {
response
.safeHeader('Content-type', 'application/json')
.stream(this.getSwaggerSpecFileContent(), () => {
return ['Unable to find file', 404]
})
}
}
private getSwaggerSpecFileContent(): ReadStream {
const filePath = join(this.app.appRoot, this.config.get('swagger.specFilePath'))
return fs.createReadStream(filePath)
}
}