-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
180 lines (153 loc) · 5.63 KB
/
index.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* Copyright 2023 Kapeta Inc.
* SPDX-License-Identifier: MIT
*/
import { ConfigProvider } from '@kapeta/sdk-config';
import express, { Express, RequestHandler, Router } from 'express';
import { applyWebpackHandlers } from './src/webpack';
import { TemplatesOverrides } from './src/templates';
const HEALTH_ENDPOINT = '/.kapeta/health';
export * from './src/helpers';
export * from './src/templates';
export type * from './src/webpack';
export type ServerOptions = {
disableErrorHandling?: boolean;
disableCatchAll?: boolean;
disableHealthCheck?: boolean;
};
//We want dates as numbers
const JSONStringifyReplacer = function (this: any, key: string, value: any) {
if (this[key] instanceof Date) {
return this[key].getTime();
}
return value;
};
export type ServerPortType = 'rest' | 'web' | 'http';
export const isDevMode = () => {
return !!(process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase() === 'development');
};
export class Server {
/**
* Underlying express app
*/
private readonly _express: Express;
private readonly _options: ServerOptions;
private readonly _config: ConfigProvider;
private _serverPort?: number;
private _serverHost?: string;
constructor(config: ConfigProvider, options: ServerOptions = {}) {
this._config = config;
this._express = express();
this._options = options;
//Configure health endpoint as first route
if (!this._options?.disableHealthCheck) {
this.configureHealthCheck();
}
this._express.set('json replacer', JSONStringifyReplacer);
}
/**
* Get access to the express app to make changes, add filters etc. directly
*/
public express() {
return this._express;
}
public config() {
return this._config;
}
public use(...handlers: RequestHandler[]) {
this._express.use(...handlers);
}
/**
* @See configureFrontend
*
* @deprecated Use configureFrontend instead
*/
public configureAssets(distFolder: string, webpackConfig: any, templateOverrides?: TemplatesOverrides) {
applyWebpackHandlers(distFolder, webpackConfig, this._express, templateOverrides);
}
/**
* Configures the routes for the frontend assets built by webpack
*
* In development mode, this will be using hot-reload and be served from memory
* In production mode, this will be served from the provided dist folder on disk
*
* @param distFolder The folder where the webpack build is located. Usually "./dist"
* @param webpackConfig The webpack dev config object. Usually require('../../webpack.development.config')
* @param templateOverrides Optional overrides for the templates used to render the main HTML pages
*/
public configureFrontend(distFolder: string, webpackConfig: any, templateOverrides?: TemplatesOverrides) {
applyWebpackHandlers(distFolder, webpackConfig, this._express, templateOverrides);
}
/**
* Starts server
*/
public start(portType: ServerPortType) {
console.log('Starting server for service: %s', this._config.getBlockReference());
this._start(portType).catch((err) => {
if (err.stack) {
console.log(err.stack);
} else {
console.log('Failed to start: %s', err);
}
});
}
protected configureErrorHandler() {
this._express.use(<express.ErrorRequestHandler>((err, _req, res, next) => {
if (res.headersSent) {
next(err);
return;
}
const errorBody = err.message ? { error: err.message } : { error: 'Unknown error' };
if (err.statusCode) {
res.status(err.statusCode).json(errorBody);
return;
}
res.status(500).json(errorBody);
}));
}
protected configureCatchAll() {
this._express.use((_req, res) => {
if (!res.headersSent) {
res.status(418).json({ error: 'Not available' });
}
});
}
protected configureHealthCheck() {
console.log('Configuring health check endpoint: %s', HEALTH_ENDPOINT);
this._express.get(HEALTH_ENDPOINT, (req, res) => {
res.status(200).json({ ok: true });
});
}
protected async _start(portType: ServerPortType) {
try {
this._serverPort = parseInt(await this._config.getServerPort(portType));
this._serverHost = await this._config.getServerHost();
} catch (err: any) {
if (err.message && err.message.indexOf('ECONN') > -1) {
if (this._config) {
throw new Error(
'Failed while connecting to cluster server at ' +
this._config.getProviderId() +
': ' +
err.message
);
}
throw new Error('Failed while connecting to cluster server: ' + err.message);
}
throw err;
}
if (!this._options?.disableErrorHandling) {
this.configureErrorHandler();
}
if (!this._options?.disableCatchAll) {
this.configureCatchAll();
}
console.log('Starting server on %s:%s', this._serverHost, this._serverPort);
return new Promise((resolve) => {
this._express.listen(this._serverPort!, this._serverHost!, () => {
console.log('Server listening on %s:%s', this._serverHost, this._serverPort);
resolve(null);
});
});
}
}