@wooksjs/event-http 0.4.10 → 0.4.12
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.
- package/dist/index.cjs +148 -251
- package/dist/index.d.ts +519 -559
- package/dist/index.mjs +148 -251
- package/package.json +12 -4
package/dist/index.mjs
CHANGED
|
@@ -6,14 +6,13 @@ import http from 'http';
|
|
|
6
6
|
|
|
7
7
|
function createHttpContext(data, options) {
|
|
8
8
|
return createEventContext({
|
|
9
|
-
event:
|
|
9
|
+
event: {
|
|
10
|
+
...data,
|
|
11
|
+
type: 'HTTP',
|
|
12
|
+
},
|
|
10
13
|
options,
|
|
11
14
|
});
|
|
12
15
|
}
|
|
13
|
-
/**
|
|
14
|
-
* Wrapper on useEventContext with HTTP event types
|
|
15
|
-
* @returns set of hooks { getCtx, restoreCtx, clearCtx, hookStore, getStore, setStore }
|
|
16
|
-
*/
|
|
17
16
|
function useHttpContext() {
|
|
18
17
|
return useEventContext('HTTP');
|
|
19
18
|
}
|
|
@@ -40,20 +39,20 @@ function useRequest() {
|
|
|
40
39
|
});
|
|
41
40
|
const reqId = useEventId().getId;
|
|
42
41
|
const forwardedIp = () => init('forwardedIp', () => {
|
|
43
|
-
var _a;
|
|
44
42
|
if (typeof req.headers[xForwardedFor] === 'string' &&
|
|
45
43
|
req.headers[xForwardedFor]) {
|
|
46
|
-
return
|
|
44
|
+
return req.headers[xForwardedFor]
|
|
47
45
|
.split(',')
|
|
48
|
-
.shift()
|
|
46
|
+
.shift()
|
|
47
|
+
?.trim();
|
|
49
48
|
}
|
|
50
49
|
else {
|
|
51
50
|
return '';
|
|
52
51
|
}
|
|
53
52
|
});
|
|
54
|
-
const remoteIp = () => init('remoteIp', () =>
|
|
53
|
+
const remoteIp = () => init('remoteIp', () => req.socket?.remoteAddress || req.connection?.remoteAddress || '');
|
|
55
54
|
function getIp(options) {
|
|
56
|
-
if (options
|
|
55
|
+
if (options?.trustProxy) {
|
|
57
56
|
return forwardedIp() || getIp();
|
|
58
57
|
}
|
|
59
58
|
else {
|
|
@@ -61,10 +60,9 @@ function useRequest() {
|
|
|
61
60
|
}
|
|
62
61
|
}
|
|
63
62
|
const getIpList = () => init('ipList', () => {
|
|
64
|
-
var _a, _b;
|
|
65
63
|
return {
|
|
66
|
-
remoteIp:
|
|
67
|
-
|
|
64
|
+
remoteIp: req.socket?.remoteAddress ||
|
|
65
|
+
req.connection?.remoteAddress ||
|
|
68
66
|
'',
|
|
69
67
|
forwarded: (req.headers[xForwardedFor] || '')
|
|
70
68
|
.split(',')
|
|
@@ -155,12 +153,12 @@ function useAuthorization() {
|
|
|
155
153
|
authorization,
|
|
156
154
|
authType,
|
|
157
155
|
authRawCredentials,
|
|
158
|
-
isBasic: () =>
|
|
159
|
-
isBearer: () =>
|
|
156
|
+
isBasic: () => authType()?.toLocaleLowerCase() === 'basic',
|
|
157
|
+
isBearer: () => authType()?.toLocaleLowerCase() === 'bearer',
|
|
160
158
|
basicCredentials: () => init('basicCredentials', () => {
|
|
161
159
|
if (authorization) {
|
|
162
160
|
const type = authType();
|
|
163
|
-
if (
|
|
161
|
+
if (type?.toLocaleLowerCase() === 'basic') {
|
|
164
162
|
const creds = Buffer.from(authRawCredentials() || '', 'base64').toString('ascii');
|
|
165
163
|
const [username, password] = creds.split(':');
|
|
166
164
|
return { username, password };
|
|
@@ -211,7 +209,6 @@ function renderCacheControl(data) {
|
|
|
211
209
|
}
|
|
212
210
|
return attrs;
|
|
213
211
|
}
|
|
214
|
-
// rfc7234#section-5.2.2
|
|
215
212
|
const cacheControlFunc = {
|
|
216
213
|
mustRevalidate: (v) => v ? 'must-revalidate' : '',
|
|
217
214
|
noCache: (v) => v ? (typeof v === 'string' ? `no-cache="${v}"` : 'no-cache') : '',
|
|
@@ -229,7 +226,6 @@ const renderExpires = (v) => typeof v === 'string' || typeof v === 'number'
|
|
|
229
226
|
? new Date(v).toUTCString()
|
|
230
227
|
: v.toUTCString();
|
|
231
228
|
const renderPragmaNoCache = (v) => (v ? 'no-cache' : '');
|
|
232
|
-
// rfc7234#section-5.2.2
|
|
233
229
|
function useSetCacheControl() {
|
|
234
230
|
const { setHeader } = useSetHeaders();
|
|
235
231
|
const setAge = (value) => {
|
|
@@ -373,12 +369,12 @@ function useSetCookie(name) {
|
|
|
373
369
|
name,
|
|
374
370
|
type: 'cookie',
|
|
375
371
|
}, {
|
|
376
|
-
get: () =>
|
|
377
|
-
set: (value) =>
|
|
372
|
+
get: () => getCookie(name)?.value,
|
|
373
|
+
set: (value) => setCookie(name, value, getCookie(name)?.attrs),
|
|
378
374
|
});
|
|
379
375
|
return attachHook(valueHook, {
|
|
380
|
-
get: () =>
|
|
381
|
-
set: (attrs) =>
|
|
376
|
+
get: () => getCookie(name)?.attrs,
|
|
377
|
+
set: (attrs) => setCookie(name, getCookie(name)?.value || '', attrs),
|
|
382
378
|
}, 'attrs');
|
|
383
379
|
}
|
|
384
380
|
|
|
@@ -417,58 +413,6 @@ function useSearchParams() {
|
|
|
417
413
|
};
|
|
418
414
|
}
|
|
419
415
|
|
|
420
|
-
/******************************************************************************
|
|
421
|
-
Copyright (c) Microsoft Corporation.
|
|
422
|
-
|
|
423
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
|
424
|
-
purpose with or without fee is hereby granted.
|
|
425
|
-
|
|
426
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
427
|
-
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
428
|
-
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
429
|
-
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
430
|
-
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
431
|
-
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
432
|
-
PERFORMANCE OF THIS SOFTWARE.
|
|
433
|
-
***************************************************************************** */
|
|
434
|
-
/* global Reflect, Promise, SuppressedError, Symbol */
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
function __awaiter(thisArg, _arguments, P, generator) {
|
|
438
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
439
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
440
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
441
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
442
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
443
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
444
|
-
});
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
function __values(o) {
|
|
448
|
-
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
449
|
-
if (m) return m.call(o);
|
|
450
|
-
if (o && typeof o.length === "number") return {
|
|
451
|
-
next: function () {
|
|
452
|
-
if (o && i >= o.length) o = void 0;
|
|
453
|
-
return { value: o && o[i++], done: !o };
|
|
454
|
-
}
|
|
455
|
-
};
|
|
456
|
-
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
function __asyncValues(o) {
|
|
460
|
-
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
461
|
-
var m = o[Symbol.asyncIterator], i;
|
|
462
|
-
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
|
463
|
-
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
|
464
|
-
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
468
|
-
var e = new Error(message);
|
|
469
|
-
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
470
|
-
};
|
|
471
|
-
|
|
472
416
|
class BaseHttpResponseRenderer {
|
|
473
417
|
render(response) {
|
|
474
418
|
if (typeof response.body === 'string' ||
|
|
@@ -700,7 +644,10 @@ class BaseHttpResponse {
|
|
|
700
644
|
for (const cookie of newCookies) {
|
|
701
645
|
removeCookie(cookie.slice(0, cookie.indexOf('=')));
|
|
702
646
|
}
|
|
703
|
-
this._headers =
|
|
647
|
+
this._headers = {
|
|
648
|
+
...headers(),
|
|
649
|
+
...this._headers,
|
|
650
|
+
};
|
|
704
651
|
const setCookie = [...newCookies, ...cookies()];
|
|
705
652
|
if (setCookie && setCookie.length) {
|
|
706
653
|
this._headers['set-cookie'] = setCookie;
|
|
@@ -725,96 +672,85 @@ class BaseHttpResponse {
|
|
|
725
672
|
logger.error(error);
|
|
726
673
|
throw error;
|
|
727
674
|
}
|
|
728
|
-
respond() {
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
675
|
+
async respond() {
|
|
676
|
+
const { rawResponse, hasResponded } = useResponse();
|
|
677
|
+
const { method, rawRequest } = useRequest();
|
|
678
|
+
const logger = useEventLogger('http-response');
|
|
679
|
+
if (hasResponded()) {
|
|
680
|
+
this.panic('The response was already sent.', logger);
|
|
681
|
+
}
|
|
682
|
+
this.mergeHeaders();
|
|
683
|
+
const res = rawResponse();
|
|
684
|
+
if (this.body instanceof Readable) {
|
|
685
|
+
const stream = this.body;
|
|
686
|
+
this.mergeStatus('ok');
|
|
687
|
+
res.writeHead(this.status, {
|
|
688
|
+
...this._headers,
|
|
689
|
+
});
|
|
690
|
+
rawRequest.once('close', () => {
|
|
691
|
+
stream.destroy();
|
|
692
|
+
});
|
|
693
|
+
if (method === 'HEAD') {
|
|
694
|
+
stream.destroy();
|
|
695
|
+
res.end();
|
|
735
696
|
}
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
res.writeHead(this.status, Object.assign({}, this._headers));
|
|
743
|
-
rawRequest.once('close', () => {
|
|
744
|
-
stream.destroy();
|
|
745
|
-
});
|
|
746
|
-
if (method === 'HEAD') {
|
|
747
|
-
stream.destroy();
|
|
748
|
-
res.end();
|
|
749
|
-
}
|
|
750
|
-
else {
|
|
751
|
-
return new Promise((resolve, reject) => {
|
|
752
|
-
stream.on('error', (e) => {
|
|
753
|
-
stream.destroy();
|
|
754
|
-
res.end();
|
|
755
|
-
reject(e);
|
|
756
|
-
});
|
|
757
|
-
stream.on('close', () => {
|
|
758
|
-
stream.destroy();
|
|
759
|
-
resolve(undefined);
|
|
760
|
-
});
|
|
761
|
-
stream.pipe(res);
|
|
697
|
+
else {
|
|
698
|
+
return new Promise((resolve, reject) => {
|
|
699
|
+
stream.on('error', (e) => {
|
|
700
|
+
stream.destroy();
|
|
701
|
+
res.end();
|
|
702
|
+
reject(e);
|
|
762
703
|
});
|
|
763
|
-
|
|
704
|
+
stream.on('close', () => {
|
|
705
|
+
stream.destroy();
|
|
706
|
+
resolve(undefined);
|
|
707
|
+
});
|
|
708
|
+
stream.pipe(res);
|
|
709
|
+
});
|
|
764
710
|
}
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
else {
|
|
772
|
-
const additionalHeaders = {};
|
|
773
|
-
if (this.body.headers.get('content-length')) {
|
|
774
|
-
additionalHeaders['content-length'] = this.body.headers.get('content-length');
|
|
775
|
-
}
|
|
776
|
-
if (this.body.headers.get('content-type')) {
|
|
777
|
-
additionalHeaders['content-type'] = this.body.headers.get('content-type');
|
|
778
|
-
}
|
|
779
|
-
res.writeHead(this.status, Object.assign(Object.assign({}, additionalHeaders), this._headers));
|
|
780
|
-
yield respondWithFetch(this.body.body, res);
|
|
781
|
-
}
|
|
711
|
+
}
|
|
712
|
+
else if (globalThis.Response &&
|
|
713
|
+
this.body instanceof Response) {
|
|
714
|
+
this.mergeFetchStatus(this.body.status);
|
|
715
|
+
if (method === 'HEAD') {
|
|
716
|
+
res.end();
|
|
782
717
|
}
|
|
783
718
|
else {
|
|
784
|
-
const
|
|
785
|
-
this.
|
|
786
|
-
|
|
787
|
-
}
|
|
788
|
-
});
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
function respondWithFetch(fetchBody, res) {
|
|
792
|
-
var _a, e_1, _b, _c;
|
|
793
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
794
|
-
if (fetchBody) {
|
|
795
|
-
try {
|
|
796
|
-
try {
|
|
797
|
-
for (var _d = true, _e = __asyncValues(fetchBody), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
|
|
798
|
-
_c = _f.value;
|
|
799
|
-
_d = false;
|
|
800
|
-
const chunk = _c;
|
|
801
|
-
res.write(chunk);
|
|
802
|
-
}
|
|
719
|
+
const additionalHeaders = {};
|
|
720
|
+
if (this.body.headers.get('content-length')) {
|
|
721
|
+
additionalHeaders['content-length'] = this.body.headers.get('content-length');
|
|
803
722
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
try {
|
|
807
|
-
if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
|
|
808
|
-
}
|
|
809
|
-
finally { if (e_1) throw e_1.error; }
|
|
723
|
+
if (this.body.headers.get('content-type')) {
|
|
724
|
+
additionalHeaders['content-type'] = this.body.headers.get('content-type');
|
|
810
725
|
}
|
|
726
|
+
res.writeHead(this.status, {
|
|
727
|
+
...additionalHeaders,
|
|
728
|
+
...this._headers,
|
|
729
|
+
});
|
|
730
|
+
await respondWithFetch(this.body.body, res);
|
|
811
731
|
}
|
|
812
|
-
|
|
813
|
-
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
const renderedBody = this.renderer.render(this);
|
|
735
|
+
this.mergeStatus(renderedBody);
|
|
736
|
+
res.writeHead(this.status, {
|
|
737
|
+
'content-length': Buffer.byteLength(renderedBody),
|
|
738
|
+
...this._headers,
|
|
739
|
+
}).end(method !== 'HEAD' ? renderedBody : '');
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
async function respondWithFetch(fetchBody, res) {
|
|
744
|
+
if (fetchBody) {
|
|
745
|
+
try {
|
|
746
|
+
for await (const chunk of fetchBody) {
|
|
747
|
+
res.write(chunk);
|
|
814
748
|
}
|
|
815
749
|
}
|
|
816
|
-
|
|
817
|
-
|
|
750
|
+
catch (e) {
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
res.end();
|
|
818
754
|
}
|
|
819
755
|
|
|
820
756
|
const preStyles = 'font-family: monospace;' +
|
|
@@ -834,9 +770,14 @@ class HttpErrorRenderer extends BaseHttpResponseRenderer {
|
|
|
834
770
|
`<head><title>${data.statusCode} ${httpStatusCodes[data.statusCode]}</title></head>` +
|
|
835
771
|
`<body><center><h1>${data.statusCode} ${httpStatusCodes[data.statusCode]}</h1></center>` +
|
|
836
772
|
`<center><h4>${data.message}</h1></center><hr color="#666">` +
|
|
837
|
-
`<center style="color: #666;"> Wooks v${"0.4.
|
|
773
|
+
`<center style="color: #666;"> Wooks v${"0.4.12"} </center>` +
|
|
838
774
|
`${keys.length
|
|
839
|
-
? `<pre style="${preStyles}">${JSON.stringify(
|
|
775
|
+
? `<pre style="${preStyles}">${JSON.stringify({
|
|
776
|
+
...data,
|
|
777
|
+
statusCode: undefined,
|
|
778
|
+
message: undefined,
|
|
779
|
+
error: undefined,
|
|
780
|
+
}, null, ' ')}</pre>`
|
|
840
781
|
: ''}` +
|
|
841
782
|
'</body></html>');
|
|
842
783
|
}
|
|
@@ -846,7 +787,12 @@ class HttpErrorRenderer extends BaseHttpResponseRenderer {
|
|
|
846
787
|
const keys = Object.keys(data).filter((key) => !['statusCode', 'error', 'message'].includes(key));
|
|
847
788
|
return (`${data.statusCode} ${httpStatusCodes[data.statusCode]}\n${data.message}` +
|
|
848
789
|
`\n\n${keys.length
|
|
849
|
-
? `${JSON.stringify(
|
|
790
|
+
? `${JSON.stringify({
|
|
791
|
+
...data,
|
|
792
|
+
statusCode: undefined,
|
|
793
|
+
message: undefined,
|
|
794
|
+
error: undefined,
|
|
795
|
+
}, null, ' ')}`
|
|
850
796
|
: ''}`);
|
|
851
797
|
}
|
|
852
798
|
renderJson(response) {
|
|
@@ -864,9 +810,8 @@ class HttpErrorRenderer extends BaseHttpResponseRenderer {
|
|
|
864
810
|
: ''}}`);
|
|
865
811
|
}
|
|
866
812
|
render(response) {
|
|
867
|
-
var _a;
|
|
868
813
|
const { acceptsJson, acceptsText, acceptsHtml } = useAccept();
|
|
869
|
-
response.status =
|
|
814
|
+
response.status = response.body?.statusCode || 500;
|
|
870
815
|
if (acceptsJson()) {
|
|
871
816
|
return this.renderJson(response);
|
|
872
817
|
}
|
|
@@ -900,7 +845,12 @@ class HttpError extends Error {
|
|
|
900
845
|
message: this.message,
|
|
901
846
|
error: httpStatusCodes[this.code],
|
|
902
847
|
}
|
|
903
|
-
:
|
|
848
|
+
: {
|
|
849
|
+
...this._body,
|
|
850
|
+
statusCode: this.code,
|
|
851
|
+
message: this.message,
|
|
852
|
+
error: httpStatusCodes[this.code],
|
|
853
|
+
};
|
|
904
854
|
}
|
|
905
855
|
attachRenderer(renderer) {
|
|
906
856
|
this.renderer = renderer;
|
|
@@ -910,11 +860,7 @@ class HttpError extends Error {
|
|
|
910
860
|
}
|
|
911
861
|
}
|
|
912
862
|
|
|
913
|
-
function createWooksResponder(
|
|
914
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
915
|
-
renderer = new BaseHttpResponseRenderer(),
|
|
916
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
917
|
-
errorRenderer = new HttpErrorRenderer()) {
|
|
863
|
+
function createWooksResponder(renderer = new BaseHttpResponseRenderer(), errorRenderer = new HttpErrorRenderer()) {
|
|
918
864
|
function createResponse(data) {
|
|
919
865
|
const { hasResponded } = useResponse();
|
|
920
866
|
if (hasResponded())
|
|
@@ -940,16 +886,16 @@ errorRenderer = new HttpErrorRenderer()) {
|
|
|
940
886
|
}
|
|
941
887
|
return {
|
|
942
888
|
createResponse,
|
|
943
|
-
respond: (data) =>
|
|
889
|
+
respond: (data) => createResponse(data)?.respond(),
|
|
944
890
|
};
|
|
945
891
|
}
|
|
946
892
|
|
|
947
893
|
class WooksHttp extends WooksAdapterBase {
|
|
948
894
|
constructor(opts, wooks) {
|
|
949
|
-
super(wooks, opts
|
|
895
|
+
super(wooks, opts?.logger, opts?.router);
|
|
950
896
|
this.opts = opts;
|
|
951
897
|
this.responder = createWooksResponder();
|
|
952
|
-
this.logger =
|
|
898
|
+
this.logger = opts?.logger || this.getLogger('wooks-http');
|
|
953
899
|
}
|
|
954
900
|
all(path, handler) {
|
|
955
901
|
return this.on('*', path, handler);
|
|
@@ -975,80 +921,42 @@ class WooksHttp extends WooksAdapterBase {
|
|
|
975
921
|
options(path, handler) {
|
|
976
922
|
return this.on('OPTIONS', path, handler);
|
|
977
923
|
}
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
985
|
-
const server = (this.server = http.createServer(this.getServerCb()));
|
|
986
|
-
return new Promise((resolve, reject) => {
|
|
987
|
-
server.once('listening', resolve);
|
|
988
|
-
server.once('error', reject);
|
|
989
|
-
server.listen(...args);
|
|
990
|
-
});
|
|
924
|
+
async listen(...args) {
|
|
925
|
+
const server = (this.server = http.createServer(this.getServerCb()));
|
|
926
|
+
return new Promise((resolve, reject) => {
|
|
927
|
+
server.once('listening', resolve);
|
|
928
|
+
server.once('error', reject);
|
|
929
|
+
server.listen(...args);
|
|
991
930
|
});
|
|
992
931
|
}
|
|
993
|
-
/**
|
|
994
|
-
* Stops the server if it was attached or passed via argument
|
|
995
|
-
* @param server
|
|
996
|
-
*/
|
|
997
932
|
close(server) {
|
|
998
933
|
const srv = server || this.server;
|
|
999
934
|
return new Promise((resolve, reject) => {
|
|
1000
|
-
srv
|
|
935
|
+
srv?.close((err) => {
|
|
1001
936
|
if (err)
|
|
1002
937
|
return reject(err);
|
|
1003
938
|
resolve(srv);
|
|
1004
939
|
});
|
|
1005
940
|
});
|
|
1006
941
|
}
|
|
1007
|
-
/**
|
|
1008
|
-
* Returns http(s) server that was attached to Wooks
|
|
1009
|
-
*
|
|
1010
|
-
* See attachServer method docs
|
|
1011
|
-
* @returns Server
|
|
1012
|
-
*/
|
|
1013
942
|
getServer() {
|
|
1014
943
|
return this.server;
|
|
1015
944
|
}
|
|
1016
|
-
/**
|
|
1017
|
-
* Attaches http(s) server instance
|
|
1018
|
-
* to Wooks.
|
|
1019
|
-
*
|
|
1020
|
-
* Use it only if you want to `close` method to stop the server.
|
|
1021
|
-
* @param server Server
|
|
1022
|
-
*/
|
|
1023
945
|
attachServer(server) {
|
|
1024
946
|
this.server = server;
|
|
1025
947
|
}
|
|
1026
948
|
respond(data) {
|
|
1027
|
-
|
|
1028
|
-
void ((_a = this.responder.respond(data)) === null || _a === void 0 ? void 0 : _a.catch((e) => {
|
|
949
|
+
void this.responder.respond(data)?.catch((e) => {
|
|
1029
950
|
this.logger.error('Uncought response exception', e);
|
|
1030
|
-
})
|
|
951
|
+
});
|
|
1031
952
|
}
|
|
1032
|
-
/**
|
|
1033
|
-
* Returns server callback function
|
|
1034
|
-
* that can be passed to any node server:
|
|
1035
|
-
* ```js
|
|
1036
|
-
* import { createHttpApp } from '@wooksjs/event-http'
|
|
1037
|
-
* import http from 'http'
|
|
1038
|
-
*
|
|
1039
|
-
* const app = createHttpApp()
|
|
1040
|
-
* const server = http.createServer(app.getServerCb())
|
|
1041
|
-
* server.listen(3000)
|
|
1042
|
-
* ```
|
|
1043
|
-
*/
|
|
1044
953
|
getServerCb() {
|
|
1045
|
-
return (req, res) =>
|
|
1046
|
-
|
|
1047
|
-
const { restoreCtx, clearCtx } = createHttpContext({ req, res }, this.mergeEventOptions((_a = this.opts) === null || _a === void 0 ? void 0 : _a.eventOptions));
|
|
954
|
+
return async (req, res) => {
|
|
955
|
+
const { restoreCtx, clearCtx } = createHttpContext({ req, res }, this.mergeEventOptions(this.opts?.eventOptions));
|
|
1048
956
|
const { handlers } = this.wooks.lookup(req.method, req.url);
|
|
1049
|
-
if (handlers ||
|
|
957
|
+
if (handlers || this.opts?.onNotFound) {
|
|
1050
958
|
try {
|
|
1051
|
-
|
|
959
|
+
await this.processHandlers(handlers || [this.opts?.onNotFound]);
|
|
1052
960
|
}
|
|
1053
961
|
catch (e) {
|
|
1054
962
|
this.logger.error('Internal error, please report', e);
|
|
@@ -1058,48 +966,37 @@ class WooksHttp extends WooksAdapterBase {
|
|
|
1058
966
|
}
|
|
1059
967
|
}
|
|
1060
968
|
else {
|
|
1061
|
-
// not found
|
|
1062
969
|
this.logger.debug(`404 Not found (${req.method})${req.url}`);
|
|
1063
970
|
this.respond(new HttpError(404));
|
|
1064
971
|
clearCtx();
|
|
1065
972
|
}
|
|
1066
|
-
}
|
|
973
|
+
};
|
|
1067
974
|
}
|
|
1068
|
-
processHandlers(handlers) {
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
975
|
+
async processHandlers(handlers) {
|
|
976
|
+
const { restoreCtx, clearCtx, store } = useHttpContext();
|
|
977
|
+
for (const [i, handler] of handlers.entries()) {
|
|
978
|
+
const isLastHandler = handlers.length === i + 1;
|
|
979
|
+
try {
|
|
980
|
+
restoreCtx();
|
|
981
|
+
const promise = handler();
|
|
982
|
+
clearCtx();
|
|
983
|
+
const result = await promise;
|
|
984
|
+
restoreCtx();
|
|
985
|
+
this.respond(result);
|
|
986
|
+
clearCtx();
|
|
987
|
+
break;
|
|
988
|
+
}
|
|
989
|
+
catch (e) {
|
|
990
|
+
this.logger.error(`Uncought route handler exception: ${store('event').get('req').url || ''}`, e);
|
|
991
|
+
if (isLastHandler) {
|
|
1080
992
|
restoreCtx();
|
|
1081
|
-
this.respond(
|
|
993
|
+
this.respond(e);
|
|
1082
994
|
clearCtx();
|
|
1083
|
-
break;
|
|
1084
|
-
}
|
|
1085
|
-
catch (e) {
|
|
1086
|
-
this.logger.error(`Uncought route handler exception: ${store('event').get('req').url || ''}`, e);
|
|
1087
|
-
if (isLastHandler) {
|
|
1088
|
-
restoreCtx();
|
|
1089
|
-
this.respond(e);
|
|
1090
|
-
clearCtx();
|
|
1091
|
-
}
|
|
1092
995
|
}
|
|
1093
996
|
}
|
|
1094
|
-
}
|
|
997
|
+
}
|
|
1095
998
|
}
|
|
1096
999
|
}
|
|
1097
|
-
/**
|
|
1098
|
-
* Factory for WooksHttp App
|
|
1099
|
-
* @param opts TWooksHttpOptions
|
|
1100
|
-
* @param wooks Wooks | WooksAdapterBase
|
|
1101
|
-
* @returns WooksHttp
|
|
1102
|
-
*/
|
|
1103
1000
|
function createHttpApp(opts, wooks) {
|
|
1104
1001
|
return new WooksHttp(opts, wooks);
|
|
1105
1002
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wooksjs/event-http",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.12",
|
|
4
4
|
"description": "@wooksjs/event-http",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -8,6 +8,14 @@
|
|
|
8
8
|
"files": [
|
|
9
9
|
"dist"
|
|
10
10
|
],
|
|
11
|
+
"exports": {
|
|
12
|
+
"./package.json": "./package.json",
|
|
13
|
+
".": {
|
|
14
|
+
"require": "./dist/index.cjs",
|
|
15
|
+
"import": "./dist/index.mjs",
|
|
16
|
+
"types": "./dist/index.d.ts"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
11
19
|
"repository": {
|
|
12
20
|
"type": "git",
|
|
13
21
|
"url": "git+https://github.com/wooksjs/wooksjs.git",
|
|
@@ -31,12 +39,12 @@
|
|
|
31
39
|
"url": "https://github.com/wooksjs/wooksjs/issues"
|
|
32
40
|
},
|
|
33
41
|
"peerDependencies": {
|
|
34
|
-
"wooks": "0.4.
|
|
42
|
+
"wooks": "0.4.12",
|
|
35
43
|
"@prostojs/router": "^0.2.1",
|
|
36
|
-
"@wooksjs/event-core": "0.4.
|
|
44
|
+
"@wooksjs/event-core": "0.4.12"
|
|
37
45
|
},
|
|
38
46
|
"dependencies": {
|
|
39
|
-
"@prostojs/logger": "^0.
|
|
47
|
+
"@prostojs/logger": "^0.4.0"
|
|
40
48
|
},
|
|
41
49
|
"homepage": "https://github.com/wooksjs/wooksjs/tree/main/packages/event-http#readme"
|
|
42
50
|
}
|