@moostjs/event-http 0.3.10 → 0.3.11

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 CHANGED
@@ -7,714 +7,660 @@ var http = require('http');
7
7
  var https = require('https');
8
8
  var eventCore = require('@wooksjs/event-core');
9
9
 
10
- /******************************************************************************
11
- Copyright (c) Microsoft Corporation.
12
-
13
- Permission to use, copy, modify, and/or distribute this software for any
14
- purpose with or without fee is hereby granted.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
17
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
19
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
20
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22
- PERFORMANCE OF THIS SOFTWARE.
23
- ***************************************************************************** */
24
- /* global Reflect, Promise */
25
-
26
-
27
- function __awaiter$1(thisArg, _arguments, P, generator) {
28
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
29
- return new (P || (P = Promise))(function (resolve, reject) {
30
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
31
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
32
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
33
- step((generator = generator.apply(thisArg, _arguments || [])).next());
34
- });
10
+ const LOGGER_TITLE = 'moost-http';
11
+ const CONTEXT_TYPE = 'HTTP';
12
+ /**
13
+ * ## Moost HTTP Adapter
14
+ *
15
+ * Moost Adapter for HTTP events
16
+ *
17
+ * ```ts
18
+ * │ // HTTP server example
19
+ * │ import { MoostHttp, Get } from '@moostjs/event-http'
20
+ * │ import { Moost, Param } from 'moost'
21
+ *
22
+ * │ class MyServer extends Moost {
23
+ * │ @Get('test/:name')
24
+ * │ test(@Param('name') name: string) {
25
+ * │ return { message: `Hello ${name}!` }
26
+ * │ }
27
+ * │ }
28
+ *
29
+ * │ const app = new MyServer()
30
+ * │ const http = new MoostHttp()
31
+ * │ app.adapter(http).listen(3000, () => {
32
+ * │ app.getLogger('MyApp').log('Up on port 3000')
33
+ * │ })
34
+ * │ app.init()
35
+ * ```
36
+ */
37
+ class MoostHttp {
38
+ constructor(httpApp) {
39
+ this.pathBuilders = {};
40
+ if (httpApp && httpApp instanceof eventHttp.WooksHttp) {
41
+ this.httpApp = httpApp;
42
+ }
43
+ else if (httpApp) {
44
+ this.httpApp = eventHttp.createHttpApp({
45
+ ...httpApp,
46
+ onNotFound: this.onNotFound.bind(this),
47
+ });
48
+ }
49
+ else {
50
+ this.httpApp = eventHttp.createHttpApp({
51
+ onNotFound: this.onNotFound.bind(this),
52
+ });
53
+ }
54
+ }
55
+ getHttpApp() {
56
+ return this.httpApp;
57
+ }
58
+ getServerCb() {
59
+ return this.httpApp.getServerCb();
60
+ }
61
+ listen(...args) {
62
+ return this.httpApp.listen(...args);
63
+ }
64
+ async onNotFound() {
65
+ const response = await moost.defineMoostEventHandler({
66
+ loggerTitle: LOGGER_TITLE,
67
+ getIterceptorHandler: () => this.moost?.getGlobalInterceptorHandler(),
68
+ getControllerInstance: () => this.moost,
69
+ callControllerMethod: () => undefined,
70
+ })();
71
+ if (!response) {
72
+ throw new eventHttp.HttpError(404, 'Resource Not Found');
73
+ }
74
+ return response;
75
+ }
76
+ onInit(moost) {
77
+ this.moost = moost;
78
+ }
79
+ getProvideRegistry() {
80
+ return infact.createProvideRegistry([eventHttp.WooksHttp, () => this.getHttpApp()], ['WooksHttp', () => this.getHttpApp()], [
81
+ http.Server,
82
+ () => this.getHttpApp().getServer(),
83
+ ], [
84
+ https.Server,
85
+ () => this.getHttpApp().getServer(),
86
+ ]);
87
+ }
88
+ getLogger() {
89
+ return this.getHttpApp().getLogger('moost-http');
90
+ }
91
+ bindHandler(opts) {
92
+ let fn;
93
+ for (const handler of opts.handlers) {
94
+ if (handler.type !== 'HTTP')
95
+ continue;
96
+ const httpPath = handler.path;
97
+ const path = typeof httpPath === 'string'
98
+ ? httpPath
99
+ : typeof opts.method === 'string'
100
+ ? opts.method
101
+ : '';
102
+ const targetPath = `${opts.prefix || ''}/${path}`.replace(/\/\/+/g, '/') + `${path.endsWith('//') ? '/' : ''}`; // explicit double slash "//" -> force url to end with slash
103
+ if (!fn) {
104
+ fn = moost.defineMoostEventHandler({
105
+ contextType: CONTEXT_TYPE,
106
+ loggerTitle: LOGGER_TITLE,
107
+ getIterceptorHandler: opts.getIterceptorHandler,
108
+ getControllerInstance: opts.getInstance,
109
+ controllerMethod: opts.method,
110
+ resolveArgs: opts.resolveArgs,
111
+ manualUnscope: true,
112
+ hooks: {
113
+ init: ({ unscope }) => {
114
+ const { rawRequest } = eventHttp.useRequest();
115
+ rawRequest.on('end', unscope); // will unscope on request end
116
+ },
117
+ },
118
+ });
119
+ }
120
+ const routerBinding = this.httpApp.on(handler.method, targetPath, fn);
121
+ const { getPath: pathBuilder } = routerBinding;
122
+ const methodMeta = moost.getMoostMate().read(opts.fakeInstance, opts.method) ||
123
+ {};
124
+ const id = (methodMeta.id || opts.method);
125
+ if (id) {
126
+ const methods = (this.pathBuilders[id] =
127
+ this.pathBuilders[id] || {});
128
+ if (handler.method === '*') {
129
+ methods.GET = pathBuilder;
130
+ methods.PUT = pathBuilder;
131
+ methods.PATCH = pathBuilder;
132
+ methods.POST = pathBuilder;
133
+ methods.DELETE = pathBuilder;
134
+ }
135
+ else {
136
+ methods[handler.method] = pathBuilder;
137
+ }
138
+ }
139
+ opts.logHandler(`${''}(${handler.method})${''}${targetPath}`);
140
+ const args = routerBinding.getArgs();
141
+ const params = {};
142
+ args.forEach(a => params[a] = `{${a}}`);
143
+ opts.register(handler, routerBinding.getPath(params), args);
144
+ }
145
+ }
35
146
  }
36
147
 
37
- const LOGGER_TITLE = 'moost-http';
38
- const CONTEXT_TYPE = 'HTTP';
39
- /**
40
- * ## Moost HTTP Adapter
41
- *
42
- * Moost Adapter for HTTP events
43
- *
44
- * ```ts
45
- * │ // HTTP server example
46
- * │ import { MoostHttp, Get } from '@moostjs/event-http'
47
- * │ import { Moost, Param } from 'moost'
48
- * │
49
- * │ class MyServer extends Moost {
50
- * │ @Get('test/:name')
51
- * │ test(@Param('name') name: string) {
52
- * │ return { message: `Hello ${name}!` }
53
- * │ }
54
- * │ }
55
- * │
56
- * │ const app = new MyServer()
57
- * │ const http = new MoostHttp()
58
- * │ app.adapter(http).listen(3000, () => {
59
- * │ app.getLogger('MyApp').log('Up on port 3000')
60
- * │ })
61
- * │ app.init()
62
- * ```
63
- */
64
- class MoostHttp {
65
- constructor(httpApp) {
66
- this.pathBuilders = {};
67
- if (httpApp && httpApp instanceof eventHttp.WooksHttp) {
68
- this.httpApp = httpApp;
69
- }
70
- else if (httpApp) {
71
- this.httpApp = eventHttp.createHttpApp(Object.assign(Object.assign({}, httpApp), { onNotFound: this.onNotFound.bind(this) }));
72
- }
73
- else {
74
- this.httpApp = eventHttp.createHttpApp({
75
- onNotFound: this.onNotFound.bind(this),
76
- });
77
- }
78
- }
79
- getHttpApp() {
80
- return this.httpApp;
81
- }
82
- getServerCb() {
83
- return this.httpApp.getServerCb();
84
- }
85
- listen(...args) {
86
- return this.httpApp.listen(...args);
87
- }
88
- onNotFound() {
89
- return __awaiter$1(this, void 0, void 0, function* () {
90
- const response = yield moost.defineMoostEventHandler({
91
- loggerTitle: LOGGER_TITLE,
92
- getIterceptorHandler: () => { var _a; return (_a = this.moost) === null || _a === void 0 ? void 0 : _a.getGlobalInterceptorHandler(); },
93
- getControllerInstance: () => this.moost,
94
- callControllerMethod: () => undefined,
95
- })();
96
- if (!response) {
97
- throw new eventHttp.HttpError(404, 'Resource Not Found');
98
- }
99
- return response;
100
- });
101
- }
102
- onInit(moost) {
103
- this.moost = moost;
104
- }
105
- getProvideRegistry() {
106
- return infact.createProvideRegistry([eventHttp.WooksHttp, () => this.getHttpApp()], ['WooksHttp', () => this.getHttpApp()], [
107
- http.Server,
108
- () => this.getHttpApp().getServer(),
109
- ], [
110
- https.Server,
111
- () => this.getHttpApp().getServer(),
112
- ]);
113
- }
114
- getLogger() {
115
- return this.getHttpApp().getLogger('moost-http');
116
- }
117
- bindHandler(opts) {
118
- let fn;
119
- for (const handler of opts.handlers) {
120
- if (handler.type !== 'HTTP')
121
- continue;
122
- const httpPath = handler.path;
123
- const path = typeof httpPath === 'string'
124
- ? httpPath
125
- : typeof opts.method === 'string'
126
- ? opts.method
127
- : '';
128
- const targetPath = `${opts.prefix || ''}/${path}`.replace(/\/\/+/g, '/') + `${path.endsWith('//') ? '/' : ''}`; // explicit double slash "//" -> force url to end with slash
129
- if (!fn) {
130
- fn = moost.defineMoostEventHandler({
131
- contextType: CONTEXT_TYPE,
132
- loggerTitle: LOGGER_TITLE,
133
- getIterceptorHandler: opts.getIterceptorHandler,
134
- getControllerInstance: opts.getInstance,
135
- controllerMethod: opts.method,
136
- resolveArgs: opts.resolveArgs,
137
- manualUnscope: true,
138
- hooks: {
139
- init: ({ unscope }) => {
140
- const { rawRequest } = eventHttp.useRequest();
141
- rawRequest.on('end', unscope); // will unscope on request end
142
- },
143
- },
144
- });
145
- }
146
- const routerBinding = this.httpApp.on(handler.method, targetPath, fn);
147
- const { getPath: pathBuilder } = routerBinding;
148
- const methodMeta = moost.getMoostMate().read(opts.fakeInstance, opts.method) ||
149
- {};
150
- const id = (methodMeta.id || opts.method);
151
- if (id) {
152
- const methods = (this.pathBuilders[id] =
153
- this.pathBuilders[id] || {});
154
- if (handler.method === '*') {
155
- methods.GET = pathBuilder;
156
- methods.PUT = pathBuilder;
157
- methods.PATCH = pathBuilder;
158
- methods.POST = pathBuilder;
159
- methods.DELETE = pathBuilder;
160
- }
161
- else {
162
- methods[handler.method] = pathBuilder;
163
- }
164
- }
165
- opts.logHandler(`${''}(${handler.method})${''}${targetPath}`);
166
- const args = routerBinding.getArgs();
167
- const params = {};
168
- args.forEach(a => params[a] = `{${a}}`);
169
- opts.register(handler, routerBinding.getPath(params), args);
170
- }
171
- }
148
+ function HttpMethod(method, path) {
149
+ return moost.getMoostMate().decorate('handlers', { method, path, type: 'HTTP' }, true);
172
150
  }
173
-
174
- function HttpMethod(method, path) {
175
- return moost.getMoostMate().decorate('handlers', { method, path, type: 'HTTP' }, true);
176
- }
177
- const All = (path) => HttpMethod('*', path);
178
- const Get = (path) => HttpMethod('GET', path);
179
- const Post = (path) => HttpMethod('POST', path);
180
- const Put = (path) => HttpMethod('PUT', path);
181
- const Delete = (path) => HttpMethod('DELETE', path);
151
+ const All = (path) => HttpMethod('*', path);
152
+ const Get = (path) => HttpMethod('GET', path);
153
+ const Post = (path) => HttpMethod('POST', path);
154
+ const Put = (path) => HttpMethod('PUT', path);
155
+ const Delete = (path) => HttpMethod('DELETE', path);
182
156
  const Patch = (path) => HttpMethod('PATCH', path);
183
157
 
184
- /******************************************************************************
185
- Copyright (c) Microsoft Corporation.
186
-
187
- Permission to use, copy, modify, and/or distribute this software for any
188
- purpose with or without fee is hereby granted.
189
-
190
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
191
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
192
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
193
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
194
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
195
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
196
- PERFORMANCE OF THIS SOFTWARE.
197
- ***************************************************************************** */
198
-
199
- function __awaiter(thisArg, _arguments, P, generator) {
200
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
201
- return new (P || (P = Promise))(function (resolve, reject) {
202
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
203
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
204
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
205
- step((generator = generator.apply(thisArg, _arguments || [])).next());
206
- });
158
+ const compressors = {
159
+ identity: {
160
+ compress: (v) => v,
161
+ uncompress: (v) => v,
162
+ },
163
+ };
164
+ async function uncompressBody(encodings, body) {
165
+ let newBody = body;
166
+ for (const e of encodings.reverse()) {
167
+ if (!compressors[e]) {
168
+ throw new Error(`Usupported compression type "${e}".`);
169
+ }
170
+ newBody = await compressors[e].uncompress(body);
171
+ }
172
+ return newBody;
207
173
  }
208
174
 
209
- const compressors = {
210
- identity: {
211
- compress: (v) => v,
212
- uncompress: (v) => v,
213
- },
214
- };
215
- function uncompressBody(encodings, body) {
216
- return __awaiter(this, void 0, void 0, function* () {
217
- let newBody = body;
218
- for (const e of encodings.reverse()) {
219
- if (!compressors[e]) {
220
- throw new Error(`Usupported compression type "${e}".`);
221
- }
222
- newBody = yield compressors[e].uncompress(body);
223
- }
224
- return newBody;
225
- });
175
+ function useBody() {
176
+ const { store } = eventHttp.useHttpContext();
177
+ const { init } = store('request');
178
+ const { rawBody } = eventHttp.useRequest();
179
+ const { 'content-type': contentType, 'content-encoding': contentEncoding } = eventHttp.useHeaders();
180
+ function contentIs(type) {
181
+ return (contentType || '').indexOf(type) >= 0;
182
+ }
183
+ const isJson = () => init('isJson', () => contentIs('application/json'));
184
+ const isHtml = () => init('isHtml', () => contentIs('text/html'));
185
+ const isXml = () => init('isXml', () => contentIs('text/xml'));
186
+ const isText = () => init('isText', () => contentIs('text/plain'));
187
+ const isBinary = () => init('isBinary', () => contentIs('application/octet-stream'));
188
+ const isFormData = () => init('isFormData', () => contentIs('multipart/form-data'));
189
+ const isUrlencoded = () => init('isUrlencoded', () => contentIs('application/x-www-form-urlencoded'));
190
+ const isCompressed = () => init('isCompressed', () => {
191
+ const parts = contentEncodings();
192
+ for (const p of parts) {
193
+ if (['deflate', 'gzip', 'br'].includes(p))
194
+ return true;
195
+ }
196
+ return false;
197
+ });
198
+ const contentEncodings = () => init('contentEncodings', () => (contentEncoding || '')
199
+ .split(',')
200
+ .map((p) => p.trim())
201
+ .filter((p) => !!p));
202
+ const parseBody = () => init('parsed', async () => {
203
+ const body = await uncompressBody(contentEncodings(), (await rawBody()).toString());
204
+ if (isJson())
205
+ return jsonParser(body);
206
+ else if (isFormData())
207
+ return formDataParser(body);
208
+ else if (isUrlencoded())
209
+ return urlEncodedParser(body);
210
+ else if (isBinary())
211
+ return textParser(body);
212
+ else
213
+ return textParser(body);
214
+ });
215
+ function jsonParser(v) {
216
+ try {
217
+ return JSON.parse(v);
218
+ }
219
+ catch (e) {
220
+ throw new eventHttp.HttpError(400, e.message);
221
+ }
222
+ }
223
+ function textParser(v) {
224
+ return v;
225
+ }
226
+ function formDataParser(v) {
227
+ const boundary = '--' +
228
+ (/boundary=([^;]+)(?:;|$)/.exec(contentType || '') || [, ''])[1];
229
+ if (!boundary)
230
+ throw new eventHttp.HttpError(eventHttp.EHttpStatusCode.BadRequest, 'form-data boundary not recognized');
231
+ const parts = v.trim().split(boundary);
232
+ const result = {};
233
+ let key = '';
234
+ let partContentType = 'text/plain';
235
+ for (const part of parts) {
236
+ parsePart();
237
+ key = '';
238
+ partContentType = 'text/plain';
239
+ let valueMode = false;
240
+ const lines = part
241
+ .trim()
242
+ .split(/\n/g)
243
+ .map((s) => s.trim());
244
+ for (const line of lines) {
245
+ if (valueMode) {
246
+ if (!result[key]) {
247
+ result[key] = line;
248
+ }
249
+ else {
250
+ result[key] += '\n' + line;
251
+ }
252
+ }
253
+ else {
254
+ if (!line || line === '--') {
255
+ valueMode = !!key;
256
+ if (valueMode) {
257
+ key = key.replace(/^["']/, '').replace(/["']$/, '');
258
+ }
259
+ continue;
260
+ }
261
+ if (line
262
+ .toLowerCase()
263
+ .startsWith('content-disposition: form-data;')) {
264
+ key = (/name=([^;]+)/.exec(line) || [])[1];
265
+ if (!key)
266
+ throw new eventHttp.HttpError(eventHttp.EHttpStatusCode.BadRequest, 'Could not read multipart name: ' + line);
267
+ continue;
268
+ }
269
+ if (line.toLowerCase().startsWith('content-type:')) {
270
+ partContentType = (/content-type:\s?([^;]+)/i.exec(line) || [])[1];
271
+ if (!partContentType)
272
+ throw new eventHttp.HttpError(eventHttp.EHttpStatusCode.BadRequest, 'Could not read content-type: ' + line);
273
+ continue;
274
+ }
275
+ }
276
+ }
277
+ }
278
+ parsePart();
279
+ function parsePart() {
280
+ if (key) {
281
+ if (partContentType.indexOf('application/json') >= 0) {
282
+ result[key] = JSON.parse(result[key]);
283
+ }
284
+ }
285
+ }
286
+ return result;
287
+ }
288
+ function urlEncodedParser(v) {
289
+ return new eventHttp.WooksURLSearchParams(v.trim()).toJson();
290
+ }
291
+ return {
292
+ isJson,
293
+ isHtml,
294
+ isXml,
295
+ isText,
296
+ isBinary,
297
+ isFormData,
298
+ isUrlencoded,
299
+ isCompressed,
300
+ contentEncodings,
301
+ parseBody,
302
+ rawBody,
303
+ };
226
304
  }
227
305
 
228
- function useBody() {
229
- const { store } = eventHttp.useHttpContext();
230
- const { init } = store('request');
231
- const { rawBody } = eventHttp.useRequest();
232
- const { 'content-type': contentType, 'content-encoding': contentEncoding } = eventHttp.useHeaders();
233
- function contentIs(type) {
234
- return (contentType || '').indexOf(type) >= 0;
235
- }
236
- const isJson = () => init('isJson', () => contentIs('application/json'));
237
- const isHtml = () => init('isHtml', () => contentIs('text/html'));
238
- const isXml = () => init('isXml', () => contentIs('text/xml'));
239
- const isText = () => init('isText', () => contentIs('text/plain'));
240
- const isBinary = () => init('isBinary', () => contentIs('application/octet-stream'));
241
- const isFormData = () => init('isFormData', () => contentIs('multipart/form-data'));
242
- const isUrlencoded = () => init('isUrlencoded', () => contentIs('application/x-www-form-urlencoded'));
243
- const isCompressed = () => init('isCompressed', () => {
244
- const parts = contentEncodings();
245
- for (const p of parts) {
246
- if (['deflate', 'gzip', 'br'].includes(p))
247
- return true;
248
- }
249
- return false;
250
- });
251
- const contentEncodings = () => init('contentEncodings', () => (contentEncoding || '')
252
- .split(',')
253
- .map((p) => p.trim())
254
- .filter((p) => !!p));
255
- const parseBody = () => init('parsed', () => __awaiter(this, void 0, void 0, function* () {
256
- const body = yield uncompressBody(contentEncodings(), (yield rawBody()).toString());
257
- if (isJson())
258
- return jsonParser(body);
259
- else if (isFormData())
260
- return formDataParser(body);
261
- else if (isUrlencoded())
262
- return urlEncodedParser(body);
263
- else if (isBinary())
264
- return textParser(body);
265
- else
266
- return textParser(body);
267
- }));
268
- function jsonParser(v) {
269
- try {
270
- return JSON.parse(v);
271
- }
272
- catch (e) {
273
- throw new eventHttp.HttpError(400, e.message);
274
- }
275
- }
276
- function textParser(v) {
277
- return v;
278
- }
279
- function formDataParser(v) {
280
- const boundary = '--' +
281
- (/boundary=([^;]+)(?:;|$)/.exec(contentType || '') || [, ''])[1];
282
- if (!boundary)
283
- throw new eventHttp.HttpError(eventHttp.EHttpStatusCode.BadRequest, 'form-data boundary not recognized');
284
- const parts = v.trim().split(boundary);
285
- const result = {};
286
- let key = '';
287
- let partContentType = 'text/plain';
288
- for (const part of parts) {
289
- parsePart();
290
- key = '';
291
- partContentType = 'text/plain';
292
- let valueMode = false;
293
- const lines = part
294
- .trim()
295
- .split(/\n/g)
296
- .map((s) => s.trim());
297
- for (const line of lines) {
298
- if (valueMode) {
299
- if (!result[key]) {
300
- result[key] = line;
301
- }
302
- else {
303
- result[key] += '\n' + line;
304
- }
305
- }
306
- else {
307
- if (!line || line === '--') {
308
- valueMode = !!key;
309
- if (valueMode) {
310
- key = key.replace(/^["']/, '').replace(/["']$/, '');
311
- }
312
- continue;
313
- }
314
- if (line
315
- .toLowerCase()
316
- .startsWith('content-disposition: form-data;')) {
317
- key = (/name=([^;]+)/.exec(line) || [])[1];
318
- if (!key)
319
- throw new eventHttp.HttpError(eventHttp.EHttpStatusCode.BadRequest, 'Could not read multipart name: ' + line);
320
- continue;
321
- }
322
- if (line.toLowerCase().startsWith('content-type:')) {
323
- partContentType = (/content-type:\s?([^;]+)/i.exec(line) || [])[1];
324
- if (!partContentType)
325
- throw new eventHttp.HttpError(eventHttp.EHttpStatusCode.BadRequest, 'Could not read content-type: ' + line);
326
- continue;
327
- }
328
- }
329
- }
330
- }
331
- parsePart();
332
- function parsePart() {
333
- if (key) {
334
- if (partContentType.indexOf('application/json') >= 0) {
335
- result[key] = JSON.parse(result[key]);
336
- }
337
- }
338
- }
339
- return result;
340
- }
341
- function urlEncodedParser(v) {
342
- return new eventHttp.WooksURLSearchParams(v.trim()).toJson();
343
- }
344
- return {
345
- isJson,
346
- isHtml,
347
- isXml,
348
- isText,
349
- isBinary,
350
- isFormData,
351
- isUrlencoded,
352
- isCompressed,
353
- contentEncodings,
354
- parseBody,
355
- rawBody,
356
- };
306
+ /**
307
+ * Hook to the Response Status
308
+ * @decorator
309
+ * @paramType TStatusHook
310
+ */
311
+ const StatusHook = () => moost.Resolve((metas, level) => {
312
+ const hook = eventHttp.useStatus();
313
+ if (level === 'PARAM') {
314
+ return hook;
315
+ }
316
+ if (level === 'PROP' && metas.instance && metas.key) {
317
+ const initialValue = metas.instance[metas.key];
318
+ eventCore.attachHook(metas.instance, {
319
+ get: () => hook.value,
320
+ set: (v) => (hook.value = v),
321
+ }, metas.key);
322
+ return typeof initialValue === 'number' ? initialValue : 200;
323
+ }
324
+ }, 'statusCode');
325
+ /**
326
+ * Hook to the Response Header
327
+ * @decorator
328
+ * @param name - header name
329
+ * @paramType THeaderHook
330
+ */
331
+ const HeaderHook = (name) => moost.Resolve((metas, level) => {
332
+ const hook = eventHttp.useSetHeader(name);
333
+ if (level === 'PARAM') {
334
+ return hook;
335
+ }
336
+ if (level === 'PROP' && metas.instance && metas.key) {
337
+ const initialValue = metas.instance[metas.key];
338
+ eventCore.attachHook(metas.instance, {
339
+ get: () => hook.value,
340
+ set: (v) => (hook.value = v),
341
+ }, metas.key);
342
+ return typeof initialValue === 'string' ? initialValue : '';
343
+ }
344
+ }, name);
345
+ /**
346
+ * Hook to the Response Cookie
347
+ * @decorator
348
+ * @param name - cookie name
349
+ * @paramType TCookieHook
350
+ */
351
+ const CookieHook = (name) => moost.Resolve((metas, level) => {
352
+ const hook = eventHttp.useSetCookie(name);
353
+ if (level === 'PARAM') {
354
+ return hook;
355
+ }
356
+ if (level === 'PROP' && metas.instance && metas.key) {
357
+ const initialValue = metas.instance[metas.key];
358
+ eventCore.attachHook(metas.instance, {
359
+ get: () => hook.value,
360
+ set: (v) => (hook.value = v),
361
+ }, metas.key);
362
+ return typeof initialValue === 'string' ? initialValue : '';
363
+ }
364
+ }, name);
365
+ /**
366
+ * Hook to the Response Cookie Attributes
367
+ * @decorator
368
+ * @param name - cookie name
369
+ * @paramType TCookieAttributes
370
+ */
371
+ const CookieAttrsHook = (name) => moost.Resolve((metas, level) => {
372
+ const hook = eventHttp.useSetCookie(name);
373
+ if (level === 'PARAM') {
374
+ return eventCore.attachHook({}, {
375
+ get: () => hook.attrs,
376
+ set: (v) => (hook.attrs = v),
377
+ });
378
+ }
379
+ if (level === 'PROP' && metas.instance && metas.key) {
380
+ const initialValue = metas.instance[metas.key];
381
+ eventCore.attachHook(metas.instance, {
382
+ get: () => hook.attrs,
383
+ set: (v) => (hook.attrs = v),
384
+ }, metas.key);
385
+ return typeof initialValue === 'object' ? initialValue : {};
386
+ }
387
+ }, name);
388
+ /**
389
+ * Parse Authorisation Header
390
+ * @decorator
391
+ * @param name - define what to take from the Auth header
392
+ * @paramType string
393
+ */
394
+ function Authorization(name) {
395
+ return moost.Resolve(() => {
396
+ const auth = eventHttp.useAuthorization();
397
+ switch (name) {
398
+ case 'username':
399
+ return auth.isBasic()
400
+ ? auth.basicCredentials()?.username
401
+ : undefined;
402
+ case 'password':
403
+ return auth.isBasic()
404
+ ? auth.basicCredentials()?.password
405
+ : undefined;
406
+ case 'bearer':
407
+ return auth.isBearer() ? auth.authorization : undefined;
408
+ case 'raw':
409
+ return auth.authRawCredentials();
410
+ case 'type':
411
+ return auth.authType();
412
+ }
413
+ }, 'authorization');
357
414
  }
358
-
359
- /**
360
- * Hook to the Response Status
361
- * @decorator
362
- * @paramType TStatusHook
363
- */
364
- const StatusHook = () => moost.Resolve((metas, level) => {
365
- const hook = eventHttp.useStatus();
366
- if (level === 'PARAM') {
367
- return hook;
368
- }
369
- if (level === 'PROP' && metas.instance && metas.key) {
370
- const initialValue = metas.instance[metas.key];
371
- eventCore.attachHook(metas.instance, {
372
- get: () => hook.value,
373
- set: (v) => (hook.value = v),
374
- }, metas.key);
375
- return typeof initialValue === 'number' ? initialValue : 200;
376
- }
377
- }, 'statusCode');
378
- /**
379
- * Hook to the Response Header
380
- * @decorator
381
- * @param name - header name
382
- * @paramType THeaderHook
383
- */
384
- const HeaderHook = (name) => moost.Resolve((metas, level) => {
385
- const hook = eventHttp.useSetHeader(name);
386
- if (level === 'PARAM') {
387
- return hook;
388
- }
389
- if (level === 'PROP' && metas.instance && metas.key) {
390
- const initialValue = metas.instance[metas.key];
391
- eventCore.attachHook(metas.instance, {
392
- get: () => hook.value,
393
- set: (v) => (hook.value = v),
394
- }, metas.key);
395
- return typeof initialValue === 'string' ? initialValue : '';
396
- }
397
- }, name);
398
- /**
399
- * Hook to the Response Cookie
400
- * @decorator
401
- * @param name - cookie name
402
- * @paramType TCookieHook
403
- */
404
- const CookieHook = (name) => moost.Resolve((metas, level) => {
405
- const hook = eventHttp.useSetCookie(name);
406
- if (level === 'PARAM') {
407
- return hook;
408
- }
409
- if (level === 'PROP' && metas.instance && metas.key) {
410
- const initialValue = metas.instance[metas.key];
411
- eventCore.attachHook(metas.instance, {
412
- get: () => hook.value,
413
- set: (v) => (hook.value = v),
414
- }, metas.key);
415
- return typeof initialValue === 'string' ? initialValue : '';
416
- }
417
- }, name);
418
- /**
419
- * Hook to the Response Cookie Attributes
420
- * @decorator
421
- * @param name - cookie name
422
- * @paramType TCookieAttributes
423
- */
424
- const CookieAttrsHook = (name) => moost.Resolve((metas, level) => {
425
- const hook = eventHttp.useSetCookie(name);
426
- if (level === 'PARAM') {
427
- return eventCore.attachHook({}, {
428
- get: () => hook.attrs,
429
- set: (v) => (hook.attrs = v),
430
- });
431
- }
432
- if (level === 'PROP' && metas.instance && metas.key) {
433
- const initialValue = metas.instance[metas.key];
434
- eventCore.attachHook(metas.instance, {
435
- get: () => hook.attrs,
436
- set: (v) => (hook.attrs = v),
437
- }, metas.key);
438
- return typeof initialValue === 'object' ? initialValue : {};
439
- }
440
- }, name);
441
- /**
442
- * Parse Authorisation Header
443
- * @decorator
444
- * @param name - define what to take from the Auth header
445
- * @paramType string
446
- */
447
- function Authorization(name) {
448
- return moost.Resolve(() => {
449
- var _a, _b;
450
- const auth = eventHttp.useAuthorization();
451
- switch (name) {
452
- case 'username':
453
- return auth.isBasic()
454
- ? (_a = auth.basicCredentials()) === null || _a === void 0 ? void 0 : _a.username
455
- : undefined;
456
- case 'password':
457
- return auth.isBasic()
458
- ? (_b = auth.basicCredentials()) === null || _b === void 0 ? void 0 : _b.password
459
- : undefined;
460
- case 'bearer':
461
- return auth.isBearer() ? auth.authorization : undefined;
462
- case 'raw':
463
- return auth.authRawCredentials();
464
- case 'type':
465
- return auth.authType();
466
- }
467
- }, 'authorization');
468
- }
469
- /**
470
- * Get Request Header Value
471
- * @decorator
472
- * @param name - header name
473
- * @paramType string
474
- */
475
- function Header(name) {
476
- return moost.Resolve(() => {
477
- const headers = eventHttp.useHeaders();
478
- return headers[name];
479
- }, 'header: ' + name);
480
- }
481
- /**
482
- * Get Request Cookie Value
483
- * @decorator
484
- * @param name - cookie name
485
- * @paramType string
486
- */
487
- function Cookie(name) {
488
- return moost.Resolve(() => eventHttp.useCookies().getCookie(name), 'cookie: ' + name);
489
- }
490
- /**
491
- * Get Query Item value or the whole parsed Query as an object
492
- * @decorator
493
- * @param name - query item name (optional)
494
- * @paramType string | object
495
- */
496
- function Query(name) {
497
- const isItem = !!name;
498
- const _name = isItem ? name : 'Query';
499
- return moost.getMoostMate().apply(moost.getMoostMate().decorate('paramSource', isItem ? 'QUERY_ITEM' : 'QUERY'), moost.getMoostMate().decorate('paramName', _name), moost.Resolve(() => {
500
- const { jsonSearchParams, urlSearchParams } = eventHttp.useSearchParams();
501
- if (isItem) {
502
- const p = urlSearchParams();
503
- const value = p.get(name);
504
- return value === null ? undefined : value;
505
- }
506
- const json = jsonSearchParams();
507
- return Object.keys(json).length ? json : undefined;
508
- }, _name));
509
- }
510
- /**
511
- * Get Requested URL
512
- * @decorator
513
- * @paramType string
514
- */
515
- function Url() {
516
- return moost.Resolve(() => eventHttp.useRequest().url || '', 'url');
517
- }
518
- /**
519
- * Get Requested HTTP Method
520
- * @decorator
521
- * @paramType string
522
- */
523
- function Method() {
524
- return moost.Resolve(() => eventHttp.useRequest().method, 'http_method');
525
- }
526
- /**
527
- * Get Raw Request Instance
528
- * @decorator
529
- * @paramType IncomingMessage
530
- */
531
- function Req() {
532
- return moost.Resolve(() => eventHttp.useRequest().rawRequest, 'request');
533
- }
534
- /**
535
- * Get Raw Response Instance
536
- * @decorator
537
- * @param opts (optional) { passthrough: boolean }
538
- * @paramType ServerResponse
539
- */
540
- function Res(opts) {
541
- return moost.Resolve(() => eventHttp.useResponse().rawResponse(opts), 'response');
542
- }
543
- /**
544
- * Get Request Unique Identificator (UUID)
545
- * @decorator
546
- * @paramType string
547
- */
548
- function ReqId() {
549
- return moost.Resolve(() => eventHttp.useRequest().reqId(), 'reqId');
550
- }
551
- /**
552
- * Get Request IP Address
553
- * @decorator
554
- * @paramType string
555
- */
556
- function Ip(opts) {
557
- return moost.Resolve(() => eventHttp.useRequest().getIp(opts), 'ip');
558
- }
559
- /**
560
- * Get Request IP Address list
561
- * @decorator
562
- * @paramType string[]
563
- */
564
- function IpList() {
565
- return moost.Resolve(() => eventHttp.useRequest().getIpList(), 'ipList');
566
- }
567
- /**
568
- * Get Parsed Request Body
569
- * @decorator
570
- * @paramType object | string | unknown
571
- */
572
- function Body() {
573
- return moost.getMoostMate().apply(moost.getMoostMate().decorate('paramSource', 'BODY'), moost.Resolve(() => useBody().parseBody(), 'body'));
574
- }
575
- /**
576
- * Get Raw Request Body Buffer
577
- * @decorator
578
- * @paramType Promise<Buffer>
579
- */
580
- function RawBody() {
581
- return moost.Resolve(() => useBody().rawBody(), 'body');
415
+ /**
416
+ * Get Request Header Value
417
+ * @decorator
418
+ * @param name - header name
419
+ * @paramType string
420
+ */
421
+ function Header(name) {
422
+ return moost.Resolve(() => {
423
+ const headers = eventHttp.useHeaders();
424
+ return headers[name];
425
+ }, 'header: ' + name);
426
+ }
427
+ /**
428
+ * Get Request Cookie Value
429
+ * @decorator
430
+ * @param name - cookie name
431
+ * @paramType string
432
+ */
433
+ function Cookie(name) {
434
+ return moost.Resolve(() => eventHttp.useCookies().getCookie(name), 'cookie: ' + name);
435
+ }
436
+ /**
437
+ * Get Query Item value or the whole parsed Query as an object
438
+ * @decorator
439
+ * @param name - query item name (optional)
440
+ * @paramType string | object
441
+ */
442
+ function Query(name) {
443
+ const isItem = !!name;
444
+ const _name = isItem ? name : 'Query';
445
+ return moost.getMoostMate().apply(moost.getMoostMate().decorate('paramSource', isItem ? 'QUERY_ITEM' : 'QUERY'), moost.getMoostMate().decorate('paramName', _name), moost.Resolve(() => {
446
+ const { jsonSearchParams, urlSearchParams } = eventHttp.useSearchParams();
447
+ if (isItem) {
448
+ const p = urlSearchParams();
449
+ const value = p.get(name);
450
+ return value === null ? undefined : value;
451
+ }
452
+ const json = jsonSearchParams();
453
+ return Object.keys(json).length ? json : undefined;
454
+ }, _name));
455
+ }
456
+ /**
457
+ * Get Requested URL
458
+ * @decorator
459
+ * @paramType string
460
+ */
461
+ function Url() {
462
+ return moost.Resolve(() => eventHttp.useRequest().url || '', 'url');
463
+ }
464
+ /**
465
+ * Get Requested HTTP Method
466
+ * @decorator
467
+ * @paramType string
468
+ */
469
+ function Method() {
470
+ return moost.Resolve(() => eventHttp.useRequest().method, 'http_method');
471
+ }
472
+ /**
473
+ * Get Raw Request Instance
474
+ * @decorator
475
+ * @paramType IncomingMessage
476
+ */
477
+ function Req() {
478
+ return moost.Resolve(() => eventHttp.useRequest().rawRequest, 'request');
479
+ }
480
+ /**
481
+ * Get Raw Response Instance
482
+ * @decorator
483
+ * @param opts (optional) { passthrough: boolean }
484
+ * @paramType ServerResponse
485
+ */
486
+ function Res(opts) {
487
+ return moost.Resolve(() => eventHttp.useResponse().rawResponse(opts), 'response');
488
+ }
489
+ /**
490
+ * Get Request Unique Identificator (UUID)
491
+ * @decorator
492
+ * @paramType string
493
+ */
494
+ function ReqId() {
495
+ return moost.Resolve(() => eventHttp.useRequest().reqId(), 'reqId');
496
+ }
497
+ /**
498
+ * Get Request IP Address
499
+ * @decorator
500
+ * @paramType string
501
+ */
502
+ function Ip(opts) {
503
+ return moost.Resolve(() => eventHttp.useRequest().getIp(opts), 'ip');
504
+ }
505
+ /**
506
+ * Get Request IP Address list
507
+ * @decorator
508
+ * @paramType string[]
509
+ */
510
+ function IpList() {
511
+ return moost.Resolve(() => eventHttp.useRequest().getIpList(), 'ipList');
512
+ }
513
+ /**
514
+ * Get Parsed Request Body
515
+ * @decorator
516
+ * @paramType object | string | unknown
517
+ */
518
+ function Body() {
519
+ return moost.getMoostMate().apply(moost.getMoostMate().decorate('paramSource', 'BODY'), moost.Resolve(() => useBody().parseBody(), 'body'));
520
+ }
521
+ /**
522
+ * Get Raw Request Body Buffer
523
+ * @decorator
524
+ * @paramType Promise<Buffer>
525
+ */
526
+ function RawBody() {
527
+ return moost.Resolve(() => useBody().rawBody(), 'body');
582
528
  }
583
529
 
584
- const setHeaderInterceptor = (name, value, opts) => {
585
- const fn = (_before, after, onError) => {
586
- const h = eventHttp.useSetHeader(name);
587
- const status = eventHttp.useStatus();
588
- const cb = () => {
589
- if ((!h.value || (opts === null || opts === void 0 ? void 0 : opts.force)) &&
590
- (!(opts === null || opts === void 0 ? void 0 : opts.status) || opts.status === status.value)) {
591
- h.value = value;
592
- }
593
- };
594
- if ((opts === null || opts === void 0 ? void 0 : opts.when) !== 'error') {
595
- after(cb);
596
- }
597
- if ((opts === null || opts === void 0 ? void 0 : opts.when) === 'always' || (opts === null || opts === void 0 ? void 0 : opts.when) === 'error') {
598
- onError(cb);
599
- }
600
- };
601
- fn.priority = moost.TInterceptorPriority.AFTER_ALL;
602
- return fn;
603
- };
604
- /**
605
- * Set Header for Request Handler
606
- *
607
- * ```ts
608
- * import { Get, SetHeader } from '@moostjs/event-http';
609
- * import { Controller } from 'moost';
610
- *
611
- * @Controller()
612
- * export class ExampleController {
613
- * @Get('test')
614
- * // setting header for request handler
615
- * @SetHeader('x-server', 'my-server')
616
- * testHandler() {
617
- * return '...'
618
- * }
619
- * }
620
- * ```
621
- *
622
- * ```ts
623
- * import { Get, SetHeader } from '@moostjs/event-http';
624
- * import { Controller } from 'moost';
625
- *
626
- * @Controller()
627
- * export class ExampleController {
628
- * @Get('test')
629
- * // setting header only if status = 400
630
- * @SetHeader('content-type', 'text/plain', { status: 400 })
631
- * testHandler() {
632
- * return '...'
633
- * }
634
- * }
635
- * ```
636
- *
637
- * @param name name of header
638
- * @param value value for header
639
- * @param options options { status?: number, force?: boolean }
640
- */
641
- function SetHeader(...args) {
642
- return moost.Intercept(setHeaderInterceptor(...args));
643
- }
644
- const setCookieInterceptor = (name, value, attrs) => {
645
- const fn = (before, after) => {
646
- const { setCookie, getCookie } = eventHttp.useSetCookies();
647
- after(() => {
648
- if (!getCookie(name)) {
649
- setCookie(name, value, attrs);
650
- }
651
- });
652
- };
653
- fn.priority = moost.TInterceptorPriority.AFTER_ALL;
654
- return fn;
655
- };
656
- /**
657
- * Set Cookie for Request Handler
658
- * ```ts
659
- * import { Get, SetCookie } from '@moostjs/event-http';
660
- * import { Controller } from 'moost';
661
- *
662
- * @Controller()
663
- * export class ExampleController {
664
- * @Get('test')
665
- * // setting 'my-cookie' = 'value' with maxAge of 10 minutes
666
- * @SetCookie('my-cookie', 'value', { maxAge: '10m' })
667
- * testHandler() {
668
- * return '...'
669
- * }
670
- * }
671
- * ```
672
- *
673
- * @param name name of cookie
674
- * @param value value for cookie
675
- * @param attrs cookie attributes
676
- */
677
- function SetCookie(...args) {
678
- return moost.Intercept(setCookieInterceptor(...args));
679
- }
680
- const setStatusInterceptor = (code, opts) => {
681
- return moost.defineInterceptorFn((before, after) => {
682
- const status = eventHttp.useStatus();
683
- after(() => {
684
- if (!status.isDefined || (opts === null || opts === void 0 ? void 0 : opts.force)) {
685
- status.value = code;
686
- }
687
- });
688
- });
689
- };
690
- /**
691
- * Set Response Status for Request Handler
692
- *
693
- * ```ts
694
- * import { Get, SetStatus } from '@moostjs/event-http';
695
- * import { Controller } from 'moost';
696
- *
697
- * @Controller()
698
- * export class ExampleController {
699
- * @Get('test')
700
- * @SetStatus(201)
701
- * testHandler() {
702
- * return '...'
703
- * }
704
- * }
705
- * ```
706
- * @param code number
707
- * @param opts optional { force?: boolean }
708
- */
709
- function SetStatus(...args) {
710
- return moost.Intercept(setStatusInterceptor(...args));
530
+ const setHeaderInterceptor = (name, value, opts) => {
531
+ const fn = (_before, after, onError) => {
532
+ const h = eventHttp.useSetHeader(name);
533
+ const status = eventHttp.useStatus();
534
+ const cb = () => {
535
+ if ((!h.value || opts?.force) &&
536
+ (!opts?.status || opts.status === status.value)) {
537
+ h.value = value;
538
+ }
539
+ };
540
+ if (opts?.when !== 'error') {
541
+ after(cb);
542
+ }
543
+ if (opts?.when === 'always' || opts?.when === 'error') {
544
+ onError(cb);
545
+ }
546
+ };
547
+ fn.priority = moost.TInterceptorPriority.AFTER_ALL;
548
+ return fn;
549
+ };
550
+ /**
551
+ * Set Header for Request Handler
552
+ *
553
+ * ```ts
554
+ * import { Get, SetHeader } from '@moostjs/event-http';
555
+ * import { Controller } from 'moost';
556
+ *
557
+ * @Controller()
558
+ * export class ExampleController {
559
+ * @Get('test')
560
+ * // setting header for request handler
561
+ * @SetHeader('x-server', 'my-server')
562
+ * testHandler() {
563
+ * return '...'
564
+ * }
565
+ * }
566
+ * ```
567
+ *
568
+ * ```ts
569
+ * import { Get, SetHeader } from '@moostjs/event-http';
570
+ * import { Controller } from 'moost';
571
+ *
572
+ * @Controller()
573
+ * export class ExampleController {
574
+ * @Get('test')
575
+ * // setting header only if status = 400
576
+ * @SetHeader('content-type', 'text/plain', { status: 400 })
577
+ * testHandler() {
578
+ * return '...'
579
+ * }
580
+ * }
581
+ * ```
582
+ *
583
+ * @param name name of header
584
+ * @param value value for header
585
+ * @param options options { status?: number, force?: boolean }
586
+ */
587
+ function SetHeader(...args) {
588
+ return moost.Intercept(setHeaderInterceptor(...args));
589
+ }
590
+ const setCookieInterceptor = (name, value, attrs) => {
591
+ const fn = (before, after) => {
592
+ const { setCookie, getCookie } = eventHttp.useSetCookies();
593
+ after(() => {
594
+ if (!getCookie(name)) {
595
+ setCookie(name, value, attrs);
596
+ }
597
+ });
598
+ };
599
+ fn.priority = moost.TInterceptorPriority.AFTER_ALL;
600
+ return fn;
601
+ };
602
+ /**
603
+ * Set Cookie for Request Handler
604
+ * ```ts
605
+ * import { Get, SetCookie } from '@moostjs/event-http';
606
+ * import { Controller } from 'moost';
607
+ *
608
+ * @Controller()
609
+ * export class ExampleController {
610
+ * @Get('test')
611
+ * // setting 'my-cookie' = 'value' with maxAge of 10 minutes
612
+ * @SetCookie('my-cookie', 'value', { maxAge: '10m' })
613
+ * testHandler() {
614
+ * return '...'
615
+ * }
616
+ * }
617
+ * ```
618
+ *
619
+ * @param name name of cookie
620
+ * @param value value for cookie
621
+ * @param attrs cookie attributes
622
+ */
623
+ function SetCookie(...args) {
624
+ return moost.Intercept(setCookieInterceptor(...args));
625
+ }
626
+ const setStatusInterceptor = (code, opts) => {
627
+ return moost.defineInterceptorFn((before, after) => {
628
+ const status = eventHttp.useStatus();
629
+ after(() => {
630
+ if (!status.isDefined || opts?.force) {
631
+ status.value = code;
632
+ }
633
+ });
634
+ });
635
+ };
636
+ /**
637
+ * Set Response Status for Request Handler
638
+ *
639
+ * ```ts
640
+ * import { Get, SetStatus } from '@moostjs/event-http';
641
+ * import { Controller } from 'moost';
642
+ *
643
+ * @Controller()
644
+ * export class ExampleController {
645
+ * @Get('test')
646
+ * @SetStatus(201)
647
+ * testHandler() {
648
+ * return '...'
649
+ * }
650
+ * }
651
+ * ```
652
+ * @param code number
653
+ * @param opts optional { force?: boolean }
654
+ */
655
+ function SetStatus(...args) {
656
+ return moost.Intercept(setStatusInterceptor(...args));
711
657
  }
712
658
 
713
- Object.defineProperty(exports, 'HttpError', {
659
+ Object.defineProperty(exports, "HttpError", {
714
660
  enumerable: true,
715
661
  get: function () { return eventHttp.HttpError; }
716
662
  });
717
- Object.defineProperty(exports, 'useHttpContext', {
663
+ Object.defineProperty(exports, "useHttpContext", {
718
664
  enumerable: true,
719
665
  get: function () { return eventHttp.useHttpContext; }
720
666
  });