@opra/core 0.25.5 → 0.26.0

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.
Files changed (63) hide show
  1. package/cjs/augmentation/container.augmentation.js +2 -0
  2. package/cjs/http/adapters/express-adapter.host.js +34 -0
  3. package/cjs/http/{express-adapter.js → adapters/express-adapter.js} +1 -3
  4. package/cjs/http/{http-adapter.host.js → adapters/node-http-adapter.host.js} +30 -22
  5. package/cjs/http/adapters/node-http-adapter.js +14 -0
  6. package/cjs/http/helpers/json-body-loader.js +29 -0
  7. package/cjs/http/http-adapter-host.js +678 -0
  8. package/cjs/index.js +4 -3
  9. package/cjs/platform-adapter.host.js +74 -45
  10. package/cjs/{endpoint-context.js → request-context.js} +5 -5
  11. package/cjs/request.host.js +3 -0
  12. package/esm/augmentation/container.augmentation.js +1 -0
  13. package/esm/http/adapters/express-adapter.host.js +30 -0
  14. package/esm/http/{express-adapter.js → adapters/express-adapter.js} +1 -3
  15. package/esm/http/{http-adapter.host.js → adapters/node-http-adapter.host.js} +28 -20
  16. package/esm/http/adapters/node-http-adapter.js +11 -0
  17. package/esm/http/helpers/json-body-loader.js +24 -0
  18. package/esm/http/http-adapter-host.js +673 -0
  19. package/esm/index.js +4 -3
  20. package/esm/platform-adapter.host.js +75 -46
  21. package/esm/{endpoint-context.js → request-context.js} +4 -4
  22. package/esm/request.host.js +3 -0
  23. package/i18n/en/error.json +1 -2
  24. package/package.json +3 -3
  25. package/types/augmentation/collection.augmentation.d.ts +19 -16
  26. package/types/augmentation/container.augmentation.d.ts +13 -0
  27. package/types/augmentation/resource.augmentation.d.ts +2 -2
  28. package/types/augmentation/singleton.augmentation.d.ts +13 -9
  29. package/types/augmentation/storage.augmentation.d.ts +11 -14
  30. package/types/http/{express-adapter.d.ts → adapters/express-adapter.d.ts} +3 -3
  31. package/types/http/adapters/express-adapter.host.d.ts +12 -0
  32. package/types/http/{http-adapter.d.ts → adapters/node-http-adapter.d.ts} +5 -5
  33. package/types/http/adapters/node-http-adapter.host.d.ts +19 -0
  34. package/types/http/helpers/json-body-loader.d.ts +5 -0
  35. package/types/http/http-adapter-host.d.ts +34 -0
  36. package/types/index.d.ts +4 -3
  37. package/types/interfaces/request-handler.interface.d.ts +1 -1
  38. package/types/platform-adapter.d.ts +2 -2
  39. package/types/platform-adapter.host.d.ts +18 -14
  40. package/types/{endpoint-context.d.ts → request-context.d.ts} +3 -3
  41. package/types/request.d.ts +7 -2
  42. package/types/request.host.d.ts +5 -2
  43. package/cjs/http/express-adapter.host.js +0 -24
  44. package/cjs/http/http-adapter-base.js +0 -138
  45. package/cjs/http/http-adapter.js +0 -16
  46. package/cjs/http/request-handlers/entity-request-handler.js +0 -429
  47. package/cjs/http/request-handlers/parse-batch-request.js +0 -169
  48. package/cjs/http/request-handlers/request-handler-base.js +0 -37
  49. package/cjs/http/request-handlers/storage-request-handler.js +0 -139
  50. package/esm/http/express-adapter.host.js +0 -20
  51. package/esm/http/http-adapter-base.js +0 -134
  52. package/esm/http/http-adapter.js +0 -13
  53. package/esm/http/request-handlers/entity-request-handler.js +0 -424
  54. package/esm/http/request-handlers/parse-batch-request.js +0 -169
  55. package/esm/http/request-handlers/request-handler-base.js +0 -33
  56. package/esm/http/request-handlers/storage-request-handler.js +0 -134
  57. package/types/http/express-adapter.host.d.ts +0 -11
  58. package/types/http/http-adapter-base.d.ts +0 -23
  59. package/types/http/http-adapter.host.d.ts +0 -18
  60. package/types/http/request-handlers/entity-request-handler.d.ts +0 -24
  61. package/types/http/request-handlers/parse-batch-request.d.ts +0 -0
  62. package/types/http/request-handlers/request-handler-base.d.ts +0 -16
  63. package/types/http/request-handlers/storage-request-handler.d.ts +0 -23
@@ -1,429 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EntityRequestHandler = void 0;
4
- const tslib_1 = require("tslib");
5
- const body_parser_1 = tslib_1.__importDefault(require("body-parser"));
6
- const putil_varhelpers_1 = require("putil-varhelpers");
7
- const valgen = tslib_1.__importStar(require("valgen"));
8
- const common_1 = require("@opra/common");
9
- const endpoint_context_js_1 = require("../../endpoint-context.js");
10
- const request_host_js_1 = require("../../request.host.js");
11
- const response_host_js_1 = require("../../response.host.js");
12
- const query_parsers_js_1 = require("../helpers/query-parsers.js");
13
- const request_handler_base_js_1 = require("./request-handler-base.js");
14
- /**
15
- * @class EntityRequestHandler
16
- */
17
- class EntityRequestHandler extends request_handler_base_js_1.RequestHandlerBase {
18
- constructor(adapter) {
19
- super(adapter);
20
- this.adapter = adapter;
21
- this.bodyLoaders = new WeakMap();
22
- }
23
- async processRequest(executionContext) {
24
- const { incoming, outgoing } = executionContext.switchToHttp();
25
- // Parse incoming message and create Request object
26
- const request = await this.parseRequest(incoming);
27
- if (!request)
28
- return;
29
- const response = new response_host_js_1.ResponseHost({ http: outgoing });
30
- const context = endpoint_context_js_1.EndpointContext.from(executionContext, request, response);
31
- await this.callEndpoint(context);
32
- if (response.errors.length) {
33
- context.errors.push(...response.errors);
34
- return;
35
- }
36
- try {
37
- await this.sendResponse(context);
38
- }
39
- catch (e) {
40
- if (e instanceof common_1.OpraException)
41
- throw e;
42
- if (e instanceof valgen.ValidationError) {
43
- throw new common_1.InternalServerError({
44
- message: (0, common_1.translate)('error:RESPONSE_VALIDATION,', 'Response validation failed'),
45
- code: 'RESPONSE_VALIDATION',
46
- details: e.issues
47
- }, e);
48
- }
49
- throw new common_1.InternalServerError(e);
50
- }
51
- }
52
- async parseRequest(incoming) {
53
- const p = incoming.parsedUrl.path[0];
54
- const resource = this.adapter.api.getResource(p.resource, true);
55
- if (!resource)
56
- throw new common_1.BadRequestError({
57
- message: (0, common_1.translate)('error:SOURCE_NOT_FOUND,', 'Resource not found'),
58
- code: 'SOURCE_NOT_FOUND',
59
- details: {
60
- path: incoming.parsedUrl.address
61
- }
62
- });
63
- try {
64
- if (resource instanceof common_1.Collection)
65
- return await this.parseCollectionRequest(resource, incoming);
66
- if (resource instanceof common_1.Singleton)
67
- return await this.parseSingletonRequest(resource, incoming);
68
- }
69
- catch (e) {
70
- if (e instanceof common_1.OpraException)
71
- throw e;
72
- if (e instanceof valgen.ValidationError) {
73
- throw new common_1.BadRequestError({
74
- message: (0, common_1.translate)('error:REQUEST_VALIDATION,', 'Request validation failed'),
75
- code: 'REQUEST_VALIDATION',
76
- details: e.issues
77
- }, e);
78
- }
79
- throw new common_1.BadRequestError(e);
80
- }
81
- }
82
- async callEndpoint(context) {
83
- const request = context.request;
84
- const { response } = context;
85
- const resource = request.resource;
86
- // Call endpoint handler method
87
- let value;
88
- try {
89
- value = await request.controller[request.endpoint].call(request.controller, context);
90
- if (value == null)
91
- value = response.value;
92
- const { endpoint } = request;
93
- if (endpoint === 'delete' || endpoint === 'deleteMany' || endpoint === 'updateMany') {
94
- let affected = 0;
95
- if (typeof value === 'number')
96
- affected = value;
97
- if (typeof value === 'boolean')
98
- affected = value ? 1 : 0;
99
- if (typeof value === 'object')
100
- affected = value.affected || value.affectedRows ||
101
- (endpoint === 'updateMany' ? value.updated : value.deleted);
102
- response.value = affected;
103
- }
104
- else {
105
- // "get" and "update" endpoints must return the entity instance, otherwise it means resource not found
106
- if (value == null && (request.endpoint === 'get' || request.endpoint === 'update'))
107
- throw new common_1.ResourceNotFoundError(resource.name, request.key);
108
- // "findMany" endpoint should return array of entity instances
109
- if (request.endpoint === 'findMany')
110
- value = value == null ? [] : Array.isArray(value) ? value : [value];
111
- else
112
- value = value == null ? {} : Array.isArray(value) ? value[0] : value;
113
- response.value = value;
114
- }
115
- }
116
- catch (error) {
117
- response.errors.push(error);
118
- }
119
- }
120
- async sendResponse(context) {
121
- const { request, response } = context;
122
- const resource = request.resource;
123
- const outgoing = response.switchToHttp();
124
- let responseObject;
125
- if (request.endpoint === 'delete' || request.endpoint === 'deleteMany') {
126
- responseObject = {
127
- resource: resource.name,
128
- operation: 'delete',
129
- affected: response.value
130
- };
131
- }
132
- else if (request.endpoint === 'updateMany') {
133
- responseObject = {
134
- resource: resource.name,
135
- operation: 'update',
136
- affected: response.value
137
- };
138
- }
139
- else {
140
- if (!response.value)
141
- throw new common_1.InternalServerError(`"${request.endpoint}" endpoint should return value`);
142
- const encode = resource.getEncoder(request.endpoint);
143
- const data = encode(response.value, { coerce: true });
144
- if (request.endpoint === 'create')
145
- outgoing.statusCode = 201;
146
- responseObject = {
147
- resource: resource.name,
148
- endpoint: request.endpoint,
149
- data
150
- };
151
- if (request.endpoint === 'create' || request.endpoint === 'update')
152
- responseObject.affected = 1;
153
- if (request.endpoint === 'findMany' && response.count != null && response.count >= 0)
154
- responseObject.totalCount = response.count;
155
- }
156
- outgoing.statusCode = outgoing.statusCode || common_1.HttpStatusCodes.OK;
157
- const body = this.adapter._i18n.deep(responseObject);
158
- outgoing.setHeader(common_1.HttpHeaderCodes.Content_Type, 'application/opra+json; charset=utf-8');
159
- outgoing.send(JSON.stringify(body));
160
- outgoing.end();
161
- }
162
- async parseCollectionRequest(resource, incoming) {
163
- if ((incoming.method === 'POST' || incoming.method === 'PATCH') && !incoming.is('json'))
164
- throw new common_1.BadRequestError({ message: 'Unsupported Content-Type' });
165
- const contentId = incoming.headers['content-id'];
166
- const p = incoming.parsedUrl.path[0];
167
- const params = incoming.parsedUrl.searchParams;
168
- switch (incoming.method) {
169
- case 'POST': {
170
- if (p.key == null) {
171
- const endpointMeta = await this.assertEndpoint(resource, 'create');
172
- const jsonReader = this.getBodyLoader(endpointMeta);
173
- const decode = resource.getDecoder('create');
174
- let data = await jsonReader(incoming);
175
- data = decode(data, { coerce: true });
176
- const pick = (0, query_parsers_js_1.parseArrayParam)(params.get('$pick'));
177
- const omit = (0, query_parsers_js_1.parseArrayParam)(params.get('$omit'));
178
- const include = (0, query_parsers_js_1.parseArrayParam)(params.get('$include'));
179
- return new request_host_js_1.RequestHost({
180
- controller: endpointMeta.controller,
181
- http: incoming,
182
- contentId,
183
- resource,
184
- endpoint: 'create',
185
- data,
186
- params: {
187
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
188
- pick: pick && resource.normalizeFieldPath(pick),
189
- omit: omit && resource.normalizeFieldPath(omit),
190
- include: include && resource.normalizeFieldPath(include)
191
- }
192
- });
193
- }
194
- break;
195
- }
196
- case 'DELETE': {
197
- if (p.key != null) {
198
- const endpointMeta = await this.assertEndpoint(resource, 'delete');
199
- return new request_host_js_1.RequestHost({
200
- controller: endpointMeta.controller,
201
- http: incoming,
202
- contentId,
203
- resource,
204
- endpoint: 'delete',
205
- key: resource.parseKeyValue(p.key),
206
- params: this.parseParameters(incoming.parsedUrl, endpointMeta)
207
- });
208
- }
209
- const endpointMeta = await this.assertEndpoint(resource, 'deleteMany');
210
- const filter = resource.normalizeFilter(params.get('$filter'));
211
- return new request_host_js_1.RequestHost({
212
- controller: endpointMeta.controller,
213
- http: incoming,
214
- contentId,
215
- resource,
216
- endpoint: 'deleteMany',
217
- params: {
218
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
219
- filter
220
- }
221
- });
222
- }
223
- case 'GET': {
224
- const pick = (0, query_parsers_js_1.parseArrayParam)(params.get('$pick'));
225
- const omit = (0, query_parsers_js_1.parseArrayParam)(params.get('$omit'));
226
- const include = (0, query_parsers_js_1.parseArrayParam)(params.get('$include'));
227
- if (p.key != null) {
228
- const endpointMeta = await this.assertEndpoint(resource, 'get');
229
- return new request_host_js_1.RequestHost({
230
- controller: endpointMeta.controller,
231
- http: incoming,
232
- contentId,
233
- resource,
234
- endpoint: 'get',
235
- key: resource.parseKeyValue(p.key),
236
- params: {
237
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
238
- pick: pick && resource.normalizeFieldPath(pick),
239
- omit: omit && resource.normalizeFieldPath(omit),
240
- include: include && resource.normalizeFieldPath(include)
241
- }
242
- });
243
- }
244
- const endpointMeta = await this.assertEndpoint(resource, 'findMany');
245
- const filter = resource.normalizeFilter(params.get('$filter'));
246
- const sort = (0, query_parsers_js_1.parseArrayParam)(params.get('$sort'));
247
- return new request_host_js_1.RequestHost({
248
- controller: endpointMeta.controller,
249
- http: incoming,
250
- contentId,
251
- resource,
252
- endpoint: 'findMany',
253
- params: {
254
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
255
- pick: pick && resource.normalizeFieldPath(pick),
256
- omit: omit && resource.normalizeFieldPath(omit),
257
- include: include && resource.normalizeFieldPath(include),
258
- sort: sort && resource.normalizeSortFields(sort),
259
- filter,
260
- limit: (0, putil_varhelpers_1.toInt)(params.get('$limit')),
261
- skip: (0, putil_varhelpers_1.toInt)(params.get('$skip')),
262
- distinct: (0, putil_varhelpers_1.toBoolean)(params.get('$distinct')),
263
- count: (0, putil_varhelpers_1.toBoolean)(params.get('$count')),
264
- }
265
- });
266
- }
267
- case 'PATCH': {
268
- if (p.key != null) {
269
- const endpointMeta = await this.assertEndpoint(resource, 'update');
270
- const jsonReader = this.getBodyLoader(endpointMeta);
271
- const decode = resource.getDecoder('update');
272
- let data = await jsonReader(incoming);
273
- data = decode(data, { coerce: true });
274
- const pick = (0, query_parsers_js_1.parseArrayParam)(params.get('$pick'));
275
- const omit = (0, query_parsers_js_1.parseArrayParam)(params.get('$omit'));
276
- const include = (0, query_parsers_js_1.parseArrayParam)(params.get('$include'));
277
- return new request_host_js_1.RequestHost({
278
- controller: endpointMeta.controller,
279
- http: incoming,
280
- contentId,
281
- resource,
282
- endpoint: 'update',
283
- key: resource.parseKeyValue(p.key),
284
- data,
285
- params: {
286
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
287
- pick: pick && resource.normalizeFieldPath(pick),
288
- omit: omit && resource.normalizeFieldPath(omit),
289
- include: include && resource.normalizeFieldPath(include),
290
- }
291
- });
292
- }
293
- const endpointMeta = await this.assertEndpoint(resource, 'updateMany');
294
- const jsonReader = this.getBodyLoader(endpointMeta);
295
- const decode = resource.getDecoder('updateMany');
296
- let data = await jsonReader(incoming);
297
- data = decode(data, { coerce: true });
298
- const filter = resource.normalizeFilter(params.get('$filter'));
299
- return new request_host_js_1.RequestHost({
300
- controller: endpointMeta.controller,
301
- http: incoming,
302
- contentId,
303
- resource,
304
- endpoint: 'updateMany',
305
- data,
306
- params: {
307
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
308
- filter,
309
- }
310
- });
311
- }
312
- }
313
- throw new common_1.MethodNotAllowedError({
314
- message: `Collection resource do not accept http "${incoming.method}" method`
315
- });
316
- }
317
- async parseSingletonRequest(resource, incoming) {
318
- if ((incoming.method === 'POST' || incoming.method === 'PATCH') &&
319
- incoming.headers['content-type'] !== 'application/json')
320
- throw new common_1.BadRequestError({ message: 'Unsupported Content-Type' });
321
- const contentId = incoming.headers['content-id'];
322
- const params = incoming.parsedUrl.searchParams;
323
- switch (incoming.method) {
324
- case 'POST': {
325
- const endpointMeta = await this.assertEndpoint(resource, 'create');
326
- const jsonReader = this.getBodyLoader(endpointMeta);
327
- const decode = resource.getDecoder('create');
328
- let data = await jsonReader(incoming);
329
- data = decode(data, { coerce: true });
330
- const pick = (0, query_parsers_js_1.parseArrayParam)(params.get('$pick'));
331
- const omit = (0, query_parsers_js_1.parseArrayParam)(params.get('$omit'));
332
- const include = (0, query_parsers_js_1.parseArrayParam)(params.get('$include'));
333
- return new request_host_js_1.RequestHost({
334
- controller: endpointMeta.controller,
335
- http: incoming,
336
- contentId,
337
- resource,
338
- endpoint: 'create',
339
- data,
340
- params: {
341
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
342
- pick: pick && resource.normalizeFieldPath(pick),
343
- omit: omit && resource.normalizeFieldPath(omit),
344
- include: include && resource.normalizeFieldPath(include)
345
- }
346
- });
347
- }
348
- case 'DELETE': {
349
- const endpointMeta = await this.assertEndpoint(resource, 'delete');
350
- return new request_host_js_1.RequestHost({
351
- controller: endpointMeta.controller,
352
- http: incoming,
353
- contentId,
354
- resource,
355
- endpoint: 'delete',
356
- params: this.parseParameters(incoming.parsedUrl, endpointMeta)
357
- });
358
- }
359
- case 'GET': {
360
- const endpointMeta = await this.assertEndpoint(resource, 'get');
361
- const pick = (0, query_parsers_js_1.parseArrayParam)(params.get('$pick'));
362
- const omit = (0, query_parsers_js_1.parseArrayParam)(params.get('$omit'));
363
- const include = (0, query_parsers_js_1.parseArrayParam)(params.get('$include'));
364
- return new request_host_js_1.RequestHost({
365
- controller: endpointMeta.controller,
366
- http: incoming,
367
- contentId,
368
- resource,
369
- endpoint: 'get',
370
- params: {
371
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
372
- pick: pick && resource.normalizeFieldPath(pick),
373
- omit: omit && resource.normalizeFieldPath(omit),
374
- include: include && resource.normalizeFieldPath(include)
375
- }
376
- });
377
- }
378
- case 'PATCH': {
379
- const endpointMeta = await this.assertEndpoint(resource, 'update');
380
- const jsonReader = this.getBodyLoader(endpointMeta);
381
- const decode = resource.getDecoder('update');
382
- let data = await jsonReader(incoming);
383
- data = decode(data, { coerce: true });
384
- const pick = (0, query_parsers_js_1.parseArrayParam)(params.get('$pick'));
385
- const omit = (0, query_parsers_js_1.parseArrayParam)(params.get('$omit'));
386
- const include = (0, query_parsers_js_1.parseArrayParam)(params.get('$include'));
387
- return new request_host_js_1.RequestHost({
388
- controller: endpointMeta.controller,
389
- http: incoming,
390
- contentId,
391
- resource,
392
- endpoint: 'update',
393
- data,
394
- params: {
395
- ...this.parseParameters(incoming.parsedUrl, endpointMeta),
396
- pick: pick && resource.normalizeFieldPath(pick),
397
- omit: omit && resource.normalizeFieldPath(omit),
398
- include: include && resource.normalizeFieldPath(include),
399
- }
400
- });
401
- }
402
- }
403
- throw new common_1.MethodNotAllowedError({
404
- message: `Singleton resource do not accept http "${incoming.method}" method`
405
- });
406
- }
407
- getBodyLoader(endpoint) {
408
- let bodyLoader = this.bodyLoaders.get(endpoint);
409
- if (!bodyLoader) {
410
- const parser = body_parser_1.default.json({
411
- limit: endpoint.input?.maxContentSize,
412
- type: 'json'
413
- });
414
- bodyLoader = (incoming) => {
415
- return new Promise((resolve, reject) => {
416
- const next = (error) => {
417
- if (error)
418
- return reject(error);
419
- resolve(incoming.body);
420
- };
421
- parser(incoming, {}, next);
422
- });
423
- };
424
- this.bodyLoaders.set(endpoint, bodyLoader);
425
- }
426
- return bodyLoader;
427
- }
428
- }
429
- exports.EntityRequestHandler = EntityRequestHandler;
@@ -1,169 +0,0 @@
1
- "use strict";
2
- // async parseMultiPart(
3
- // context: TExecutionContext,
4
- // url: OpraURL,
5
- // headers: IncomingHttpHeaders,
6
- // input: Readable,
7
- // boundary: string
8
- // ): Promise<BatchRequestContext> {
9
- // return await new Promise((resolve, reject) => {
10
- // let _resolved = false;
11
- // const dicer = new Dicer({boundary});
12
- // const doReject = (e) => {
13
- // if (_resolved) return;
14
- // _resolved = true;
15
- // reject(e);
16
- // taskQueue.clearQueue();
17
- // dicer.destroy();
18
- // }
19
- // const taskQueue = new TaskQueue({concurrency: 1});
20
- // taskQueue.on('error', doReject);
21
- //
22
- // const queries: SingleRequestContext[] = [];
23
- // let partCounter = 0;
24
- // dicer.on('error', doReject);
25
- // dicer.on('part', part => {
26
- // const partIndex = partCounter++;
27
- // let header: any;
28
- // const chunks: Buffer[] = [];
29
- // part.on('error', doReject);
30
- // part.on('header', (_header) => header = normalizeHeaders(_header));
31
- // part.on('data', (chunk: Buffer) => chunks.push(chunk));
32
- // part.on('end', () => {
33
- // if (_resolved || !(header || chunks.length))
34
- // return;
35
- // const ct = header['content-type'];
36
- // if (ct === 'application/http') {
37
- // taskQueue.enqueue(async () => {
38
- // const data = Buffer.concat(chunks);
39
- // if (!(data && data.length))
40
- // return;
41
- // const r = HttpRequest.parse(data);
42
- // await callMiddlewares(r, [jsonBodyParser]);
43
- // const subUrl = new OpraURL(r.url);
44
- // const contentId = header && header['content-id'];
45
- // queries.push(this.parseSingleQuery({
46
- // context,
47
- // url: subUrl,
48
- // method: r.method,
49
- // headers: r.headers,
50
- // body: r.body,
51
- // contentId
52
- // }));
53
- // });
54
- // } else doReject(new BadRequestError({
55
- // message: 'Unaccepted "content-type" header in multipart data',
56
- // details: {
57
- // position: `${boundary}[${partIndex}]`
58
- // }
59
- // }))
60
- // });
61
- // });
62
- // dicer.on('finish', () => {
63
- // taskQueue.enqueue(() => {
64
- // if (_resolved) return;
65
- // _resolved = true;
66
- // const batch = new BatchRequestContext({
67
- // service: this.document,
68
- // context,
69
- // headers,
70
- // queries,
71
- // params: url.searchParams,
72
- // continueOnError: false
73
- // });
74
- // resolve(batch);
75
- // });
76
- // });
77
- // input.pipe(dicer);
78
- // });
79
- // }
80
- // protected async sendBatchResponse(context: TExecutionContext, requestContext: BatchRequestContext) {
81
- // const resp = context.getResponse();
82
- // resp.setStatus(HttpStatus.OK);
83
- // resp.setHeader(HttpHeaderCodes.Cache_Control, 'no-cache');
84
- // resp.setHeader(HttpHeaderCodes.Pragma, 'no-cache');
85
- // resp.setHeader(HttpHeaderCodes.Expires, '-1');
86
- // if (requestContext.headers) {
87
- // for (const [k, v] of Object.entries(requestContext.headers)) {
88
- // if (v)
89
- // resp.setHeader(k, v);
90
- // }
91
- // }
92
- // const boundary = 'batch_' + uuid();
93
- // resp.setHeader(HttpHeaderCodes.Content_Type, 'multipart/mixed;boundary=' + boundary);
94
- // resp.setHeader(HttpHeaderCodes.X_Opra_Version, OpraSchema.Version);
95
- //
96
- // const bodyBuilder = new HttpMultipartData();
97
- //
98
- // const chunks: any[] = [];
99
- // let msgIdx = 0;
100
- // for (const ctx of requestContext.queries) {
101
- // msgIdx++;
102
- // const out = this.createOutput(ctx);
103
- //
104
- //
105
- // // chunks.push('--' + boundary + CRLF);
106
- // // let s = 'Content-Type: application/http' + CRLF +
107
- // // 'Content-Transfer-Encoding: binary' + CRLF +
108
- // // 'Content-ID:' + (ctx.contentId || msgIdx) + CRLF +
109
- // // CRLF +
110
- // // 'HTTP/1.1 ' + out.status + (HttpStatus[out.status] || 'Unknown') + CRLF;
111
- //
112
- // let body = out.body;
113
- // const headers = out.headers || {};
114
- // if (body) {
115
- // const contentType = String(headers['content-type'] || '').split(/\s*;\s*/);
116
- // let charset = '';
117
- // if (Highland.isStream(body)) {
118
- // const l = parseInt(String(headers['content-length']), 10);
119
- // if (isNaN(l))
120
- // throw new TypeError('"content-length" header required for streamed responses');
121
- // } else if (typeof body === 'object') {
122
- // if (typeof body.stream === 'function') { // File and Blob
123
- // contentType[0] = body.type || 'binary';
124
- // headers['content-length'] = String(body.size);
125
- // body = body.stream();
126
- // } else if (Buffer.isBuffer(body)) {
127
- // headers['content-length'] = String(body.length);
128
- // } else {
129
- // contentType[0] = contentType[0] || 'application/json';
130
- // charset = 'utf-8';
131
- // body = Buffer.from(JSON.stringify(body), 'utf-8');
132
- // headers['content-length'] = String(body.length);
133
- // }
134
- // } else {
135
- // contentType[0] = contentType[0] || 'text/plain';
136
- // charset = 'utf-8';
137
- // body = Buffer.from(String(body), 'utf-8');
138
- // headers['content-length'] = String(body.length);
139
- // }
140
- // if (contentType[0]) {
141
- // if (charset) {
142
- // const i = contentType.findIndex(x => CHARSET_PATTERN.test(String(x)));
143
- // if (i > 0) contentType[i] = 'charset=' + charset;
144
- // else contentType.join('charset=' + charset);
145
- // }
146
- // headers['content-type'] = contentType.join(';');
147
- // }
148
- // }
149
- // for (const [k, v] of Object.entries(headers))
150
- // s += k + ': ' + (Array.isArray(v) ? v.join(';') : v) + CRLF
151
- //
152
- // chunks.push(s + CRLF);
153
- //
154
- // if (body) {
155
- // if (typeof body === 'string')
156
- // chunks.push(body + CRLF + CRLF);
157
- // else {
158
- // chunks.push(body);
159
- // chunks.push(CRLF + CRLF);
160
- // }
161
- // }
162
- // }
163
- //
164
- // chunks.push('--' + boundary + '--' + CRLF);
165
- //
166
- // resp.setHeader('content-type', 'multipart/mixed;boundary=' + boundary);
167
- // resp.send(Highland(chunks).flatten());
168
- // resp.end();
169
- // }
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RequestHandlerBase = void 0;
4
- const common_1 = require("@opra/common");
5
- /**
6
- * @class RequestHandlerBase
7
- */
8
- class RequestHandlerBase {
9
- constructor(adapter) {
10
- this.adapter = adapter;
11
- }
12
- async assertEndpoint(resource, endpoint) {
13
- const controller = await this.adapter.getController(resource);
14
- const endpointMeta = (typeof controller?.[endpoint] === 'function') && resource.operations[endpoint];
15
- if (endpointMeta)
16
- return {
17
- ...endpointMeta,
18
- controller
19
- };
20
- throw new common_1.ForbiddenError({
21
- message: (0, common_1.translate)('RESOLVER_FORBIDDEN', { resource: resource.name, endpoint }, `'{{resource}}' endpoint does not accept '{{endpoint}}' operations`),
22
- severity: 'error',
23
- code: 'RESOLVER_FORBIDDEN'
24
- });
25
- }
26
- parseParameters(parsedUrl, metadata) {
27
- if (!metadata.parameters)
28
- return;
29
- const searchParams = parsedUrl.searchParams;
30
- const out = {};
31
- for (const [k] of Object.entries(metadata.parameters)) {
32
- out[k] = searchParams.get(k);
33
- }
34
- return out;
35
- }
36
- }
37
- exports.RequestHandlerBase = RequestHandlerBase;