-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathapp.ts
65 lines (54 loc) · 1.83 KB
/
app.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
64
65
import compression from 'compression';
import cors from 'cors';
import express, { type Application } from 'express';
import type { IClient } from './client';
import { type IProxyOption, createProxyConfig } from './config';
import requireContentType from './content-type-checker';
import { createNewClient, createSingletonClient } from './create-client';
import { OpenApiService } from './openapi/openapi-service';
import UnleashProxy from './unleash-proxy';
export function createApp(
options: IProxyOption,
unleashClient?: IClient,
app: Application = express(),
): Application {
const config = createProxyConfig(options);
const { logger } = config;
logger.debug('Configuration:', config);
const client =
unleashClient ||
(options.clientMode === 'new'
? createNewClient(config)
: createSingletonClient(config));
const openApiService = new OpenApiService(config);
if (config.enableOAS) {
openApiService.useDocs(app);
}
const proxy = new UnleashProxy(client, config, openApiService);
app.disable('x-powered-by');
try {
app.set('trust proxy', config.trustProxy);
} catch (err) {
logger.error(
`The provided "trustProxy" option was not valid ("${config.trustProxy}")`,
err,
);
}
if (typeof options.preHook === 'function') {
options.preHook(app);
}
const corsOptions = config.cors;
app.use(cors(corsOptions));
// @ts-expect-error Express struggles with its types here, compression seems to be too old
app.use(compression());
app.use(
`${config.proxyBasePath}/proxy`,
requireContentType(),
cors(corsOptions),
express.json(),
proxy.middleware,
);
openApiService.useErrorHandler(app);
return app;
}
module.exports = { createApp };