-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
rest-explorer.controller.ts
63 lines (54 loc) · 1.78 KB
/
rest-explorer.controller.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
61
62
63
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: @loopback/rest-explorer
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {inject} from '@loopback/context';
import {
RestBindings,
RestServerConfig,
OpenApiSpecForm,
Request,
Response,
} from '@loopback/rest';
import * as ejs from 'ejs';
import * as fs from 'fs';
import * as path from 'path';
// TODO(bajtos) Allow users to customize the template
const indexHtml = path.resolve(__dirname, '../../templates/index.html.ejs');
const template = fs.readFileSync(indexHtml, 'utf-8');
const templateFn = ejs.compile(template);
export class ExplorerController {
private openApiSpecUrl: string;
constructor(
@inject(RestBindings.CONFIG, {optional: true})
restConfig: RestServerConfig = {},
@inject(RestBindings.Http.REQUEST) private request: Request,
@inject(RestBindings.Http.RESPONSE) private response: Response,
) {
this.openApiSpecUrl = this.getOpenApiSpecUrl(restConfig);
}
indexRedirect() {
this.response.redirect(301, this.request.url + '/');
}
index() {
const data = {
openApiSpecUrl: this.openApiSpecUrl,
};
const homePage = templateFn(data);
this.response
.status(200)
.contentType('text/html')
.send(homePage);
}
private getOpenApiSpecUrl(restConfig: RestServerConfig): string {
const openApiConfig = restConfig.openApiSpec || {};
const endpointMapping = openApiConfig.endpointMapping || {};
const endpoint = Object.keys(endpointMapping).find(k =>
isOpenApiV3Json(endpointMapping[k]),
);
return endpoint || '/openapi.json';
}
}
function isOpenApiV3Json(mapping: OpenApiSpecForm) {
return mapping.version === '3.0.0' && mapping.format === 'json';
}