@grest-ts/http 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,133 +1,133 @@
1
- import http from "http";
2
- import {HttpMethod, HttpStatusCode} from "@grest-ts/common";
3
- import {GGLocator, GGLocatorKey, GGLocatorScope, GGLocatorServiceType} from "@grest-ts/locator";
4
- import {GG_HTTP_SERVER} from "./GG_HTTP_SERVER";
5
- import {GGLog} from "@grest-ts/logger";
6
- import findMyWay, {HTTPMethod} from "find-my-way";
7
-
8
- export interface GGHttpServerAdapterConfig {
9
- key?: GGLocatorKey<GGHttpServer>;
10
- port?: number;
11
- }
12
-
13
- export class GGHttpServer {
14
-
15
- protected _port: number | undefined;
16
- protected teardownPromise: Promise<void> | undefined;
17
- protected readonly scope: GGLocatorScope;
18
- protected readonly runtimeName: string;
19
- private readonly configuredPort: number;
20
-
21
- private readonly _onStart: Array<() => void> = [];
22
- private readonly _onTeardown: Array<() => void> = [];
23
-
24
- public readonly httpServer: http.Server;
25
- private activeRequests = 0;
26
- private router = findMyWay<findMyWay.HTTPVersion.V1>();
27
-
28
- constructor(config?: GGHttpServerAdapterConfig) {
29
-
30
- this.runtimeName = GGLocator.getScope().serviceName;
31
- this.scope = GGLocator.getScope();
32
- this.configuredPort = config?.port ?? (process.env.PORT ? Number(process.env.PORT) : 0);
33
-
34
- GGLocator.getScope().setWithLifecycle(config?.key ?? GG_HTTP_SERVER, this, {
35
- type: GGLocatorServiceType.HTTP,
36
- start: this.start.bind(this),
37
- teardown: this.teardown.bind(this)
38
- });
39
-
40
- this.httpServer = http.createServer(async (req, res) => {
41
- if (this.teardownPromise) {
42
- res.statusCode = HttpStatusCode.ServerTemporarilyNotAvailable503;
43
- res.end();
44
- return;
45
- }
46
- this.activeRequests++;
47
- try {
48
- if (req.headers.origin) { // For browsers
49
- res.setHeader('Access-Control-Allow-Origin', '*');
50
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
51
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-company-auth'); // @TODO Remove x-company-auth
52
- res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
53
- }
54
- if (req.method === 'OPTIONS') {
55
- res.writeHead(204);
56
- res.end();
57
- } else {
58
- const resolved = this.router.find(req.method as HTTPMethod, req.url)
59
- if (resolved) {
60
- await (resolved.handler as unknown as GGHttpRequestCallback)(req, res);
61
- } else {
62
- res.writeHead(404);
63
- res.end();
64
- }
65
- }
66
- } catch (error) {
67
- GGLog.error(this, error);
68
- res.writeHead(500);
69
- res.end();
70
- } finally {
71
- this.activeRequests--;
72
- }
73
- });
74
- }
75
-
76
- /**
77
- * Current port the server is listening to.
78
- * May be undefined before start() is called.
79
- */
80
- get port(): number | undefined {
81
- return this._port;
82
- }
83
-
84
- // =========================================================================
85
- // Common implementation
86
- // =========================================================================
87
-
88
- public registerRoute(method: HttpMethod, path: string, handler: GGHttpRequestCallback): void {
89
- this.router.on(method as HTTPMethod, path, handler as unknown as findMyWay.Handler<findMyWay.HTTPVersion.V1>);
90
- }
91
-
92
- public async start(): Promise<void> {
93
- this._port = await new Promise((resolve) => {
94
- this.httpServer.listen(this.configuredPort, '0.0.0.0', () => {
95
- const port = (this.httpServer.address() as any).port;
96
- resolve(port);
97
- });
98
- });
99
- this._onStart.forEach(callback => callback());
100
- GGLog.info(this, `HTTP server started`, {
101
- port: this._port,
102
- runtime: this.runtimeName
103
- });
104
- }
105
-
106
- public async teardown(): Promise<void> {
107
- if (this.teardownPromise) {
108
- return this.teardownPromise;
109
- }
110
- return this.teardownPromise = (async () => {
111
- await Promise.all(this._onTeardown.map(callback => callback()));
112
- this.httpServer.close();
113
- const maxWaitTime = 3000;
114
- const deadline = performance.now() + maxWaitTime;
115
- while (this.activeRequests > 0 && performance.now() < deadline) {
116
- await new Promise(resolve => setTimeout(resolve, 25));
117
- }
118
- GGLog.info(this, `HTTP server stopped`);
119
- })();
120
- }
121
-
122
- public onStart(callback: () => Promise<void> | void): this {
123
- this._onStart.push(callback);
124
- return this;
125
- }
126
-
127
- public onTeardown(callback: () => Promise<void> | void): this {
128
- this._onTeardown.push(callback);
129
- return this;
130
- }
131
- }
132
-
133
- export type GGHttpRequestCallback = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void>;
1
+ import http from "http";
2
+ import {HttpMethod, HttpStatusCode} from "@grest-ts/common";
3
+ import {GGLocator, GGLocatorKey, GGLocatorScope, GGLocatorServiceType} from "@grest-ts/locator";
4
+ import {GG_HTTP_SERVER} from "./GG_HTTP_SERVER";
5
+ import {GGLog} from "@grest-ts/logger";
6
+ import findMyWay, {HTTPMethod} from "find-my-way";
7
+
8
+ export interface GGHttpServerAdapterConfig {
9
+ key?: GGLocatorKey<GGHttpServer>;
10
+ port?: number;
11
+ }
12
+
13
+ export class GGHttpServer {
14
+
15
+ protected _port: number | undefined;
16
+ protected teardownPromise: Promise<void> | undefined;
17
+ protected readonly scope: GGLocatorScope;
18
+ protected readonly runtimeName: string;
19
+ private readonly configuredPort: number;
20
+
21
+ private readonly _onStart: Array<() => void> = [];
22
+ private readonly _onTeardown: Array<() => void> = [];
23
+
24
+ public readonly httpServer: http.Server;
25
+ private activeRequests = 0;
26
+ private router = findMyWay<findMyWay.HTTPVersion.V1>();
27
+
28
+ constructor(config?: GGHttpServerAdapterConfig) {
29
+
30
+ this.runtimeName = GGLocator.getScope().serviceName;
31
+ this.scope = GGLocator.getScope();
32
+ this.configuredPort = config?.port ?? (process.env.PORT ? Number(process.env.PORT) : 0);
33
+
34
+ GGLocator.getScope().setWithLifecycle(config?.key ?? GG_HTTP_SERVER, this, {
35
+ type: GGLocatorServiceType.HTTP,
36
+ start: this.start.bind(this),
37
+ teardown: this.teardown.bind(this)
38
+ });
39
+
40
+ this.httpServer = http.createServer(async (req, res) => {
41
+ if (this.teardownPromise) {
42
+ res.statusCode = HttpStatusCode.ServerTemporarilyNotAvailable503;
43
+ res.end();
44
+ return;
45
+ }
46
+ this.activeRequests++;
47
+ try {
48
+ if (req.headers.origin) { // For browsers
49
+ res.setHeader('Access-Control-Allow-Origin', '*');
50
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
51
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-company-auth'); // @TODO Remove x-company-auth
52
+ res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
53
+ }
54
+ if (req.method === 'OPTIONS') {
55
+ res.writeHead(204);
56
+ res.end();
57
+ } else {
58
+ const resolved = this.router.find(req.method as HTTPMethod, req.url)
59
+ if (resolved) {
60
+ await (resolved.handler as unknown as GGHttpRequestCallback)(req, res);
61
+ } else {
62
+ res.writeHead(404);
63
+ res.end();
64
+ }
65
+ }
66
+ } catch (error) {
67
+ GGLog.error(this, error);
68
+ res.writeHead(500);
69
+ res.end();
70
+ } finally {
71
+ this.activeRequests--;
72
+ }
73
+ });
74
+ }
75
+
76
+ /**
77
+ * Current port the server is listening to.
78
+ * May be undefined before start() is called.
79
+ */
80
+ get port(): number | undefined {
81
+ return this._port;
82
+ }
83
+
84
+ // =========================================================================
85
+ // Common implementation
86
+ // =========================================================================
87
+
88
+ public registerRoute(method: HttpMethod, path: string, handler: GGHttpRequestCallback): void {
89
+ this.router.on(method as HTTPMethod, path, handler as unknown as findMyWay.Handler<findMyWay.HTTPVersion.V1>);
90
+ }
91
+
92
+ public async start(): Promise<void> {
93
+ this._port = await new Promise((resolve) => {
94
+ this.httpServer.listen(this.configuredPort, '0.0.0.0', () => {
95
+ const port = (this.httpServer.address() as any).port;
96
+ resolve(port);
97
+ });
98
+ });
99
+ this._onStart.forEach(callback => callback());
100
+ GGLog.info(this, `HTTP server started`, {
101
+ port: this._port,
102
+ runtime: this.runtimeName
103
+ });
104
+ }
105
+
106
+ public async teardown(): Promise<void> {
107
+ if (this.teardownPromise) {
108
+ return this.teardownPromise;
109
+ }
110
+ return this.teardownPromise = (async () => {
111
+ await Promise.all(this._onTeardown.map(callback => callback()));
112
+ this.httpServer.close();
113
+ const maxWaitTime = 3000;
114
+ const deadline = performance.now() + maxWaitTime;
115
+ while (this.activeRequests > 0 && performance.now() < deadline) {
116
+ await new Promise(resolve => setTimeout(resolve, 25));
117
+ }
118
+ GGLog.info(this, `HTTP server stopped`);
119
+ })();
120
+ }
121
+
122
+ public onStart(callback: () => Promise<void> | void): this {
123
+ this._onStart.push(callback);
124
+ return this;
125
+ }
126
+
127
+ public onTeardown(callback: () => Promise<void> | void): this {
128
+ this._onTeardown.push(callback);
129
+ return this;
130
+ }
131
+ }
132
+
133
+ export type GGHttpRequestCallback = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void>;
@@ -1,12 +1,12 @@
1
- import {GGContextKey} from "@grest-ts/context";
2
- import {IsNumber, IsObject, IsString} from "@grest-ts/schema";
3
-
4
- const IsHttpRequestContext = IsObject({
5
- port: IsNumber,
6
- method: IsString,
7
- path: IsString,
8
- pathTemplate: IsString.orUndefined
9
- });
10
- export type HttpRequestContext = typeof IsHttpRequestContext.infer;
11
-
12
- export const GG_HTTP_REQUEST = new GGContextKey<HttpRequestContext>('http-request', IsHttpRequestContext);
1
+ import {GGContextKey} from "@grest-ts/context";
2
+ import {IsNumber, IsObject, IsString} from "@grest-ts/schema";
3
+
4
+ const IsHttpRequestContext = IsObject({
5
+ port: IsNumber,
6
+ method: IsString,
7
+ path: IsString,
8
+ pathTemplate: IsString.orUndefined
9
+ });
10
+ export type HttpRequestContext = typeof IsHttpRequestContext.infer;
11
+
12
+ export const GG_HTTP_REQUEST = new GGContextKey<HttpRequestContext>('http-request', IsHttpRequestContext);
@@ -1,4 +1,4 @@
1
- import {GGLocatorKey} from "@grest-ts/locator";
2
- import {GGHttpServer} from "./GGHttpServer";
3
-
4
- export const GG_HTTP_SERVER = new GGLocatorKey<GGHttpServer>("GGHttpServer");
1
+ import {GGLocatorKey} from "@grest-ts/locator";
2
+ import {GGHttpServer} from "./GGHttpServer";
3
+
4
+ export const GG_HTTP_SERVER = new GGLocatorKey<GGHttpServer>("GGHttpServer");