@opra/core 0.3.0 → 0.4.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 (52) hide show
  1. package/cjs/adapter/adapter.js +319 -0
  2. package/cjs/{implementation → adapter}/express-adapter.js +3 -6
  3. package/cjs/adapter/http-adapter.js +242 -0
  4. package/cjs/adapter/metadata-resource.js +23 -0
  5. package/cjs/{implementation → adapter}/query-context.js +1 -1
  6. package/cjs/enums/http-headers.enum.js +1 -1
  7. package/cjs/{implementation → helpers}/headers-map.js +2 -2
  8. package/cjs/index.js +6 -5
  9. package/cjs/interfaces/resource.interface.js +2 -0
  10. package/cjs/services/json-collection-service.js +14 -14
  11. package/cjs/services/json-singleton-service.js +97 -0
  12. package/esm/{implementation → adapter}/adapter.d.ts +17 -9
  13. package/esm/adapter/adapter.js +315 -0
  14. package/esm/{implementation → adapter}/express-adapter.d.ts +2 -2
  15. package/esm/{implementation → adapter}/express-adapter.js +3 -6
  16. package/esm/{implementation → adapter}/http-adapter.d.ts +2 -3
  17. package/esm/adapter/http-adapter.js +238 -0
  18. package/esm/adapter/metadata-resource.d.ts +8 -0
  19. package/esm/adapter/metadata-resource.js +20 -0
  20. package/esm/{implementation → adapter}/query-context.d.ts +6 -6
  21. package/esm/{implementation → adapter}/query-context.js +1 -1
  22. package/esm/enums/http-headers.enum.d.ts +1 -1
  23. package/esm/enums/http-headers.enum.js +1 -1
  24. package/esm/{implementation → helpers}/headers-map.d.ts +1 -1
  25. package/esm/{implementation → helpers}/headers-map.js +1 -1
  26. package/esm/index.d.ts +6 -5
  27. package/esm/index.js +6 -5
  28. package/esm/interfaces/resource.interface.d.ts +22 -0
  29. package/esm/interfaces/resource.interface.js +1 -0
  30. package/esm/services/json-collection-service.d.ts +11 -12
  31. package/esm/services/json-collection-service.js +15 -15
  32. package/esm/services/json-singleton-service.d.ts +39 -0
  33. package/esm/services/json-singleton-service.js +92 -0
  34. package/esm/types.d.ts +2 -8
  35. package/esm/utils/create-i18n.d.ts +1 -1
  36. package/package.json +15 -13
  37. package/cjs/implementation/adapter-utils/entity-resource-execute.util.js +0 -86
  38. package/cjs/implementation/adapter-utils/resource-execute.util.js +0 -11
  39. package/cjs/implementation/adapter-utils/resource-prepare.util.js +0 -11
  40. package/cjs/implementation/adapter.js +0 -130
  41. package/cjs/implementation/http-adapter.js +0 -253
  42. package/cjs/interfaces/entity-service.interface.js +0 -30
  43. package/esm/implementation/adapter-utils/entity-resource-execute.util.d.ts +0 -3
  44. package/esm/implementation/adapter-utils/entity-resource-execute.util.js +0 -82
  45. package/esm/implementation/adapter-utils/resource-execute.util.d.ts +0 -3
  46. package/esm/implementation/adapter-utils/resource-execute.util.js +0 -7
  47. package/esm/implementation/adapter-utils/resource-prepare.util.d.ts +0 -3
  48. package/esm/implementation/adapter-utils/resource-prepare.util.js +0 -7
  49. package/esm/implementation/adapter.js +0 -126
  50. package/esm/implementation/http-adapter.js +0 -249
  51. package/esm/interfaces/entity-service.interface.d.ts +0 -19
  52. package/esm/interfaces/entity-service.interface.js +0 -26
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OpraAdapter = void 0;
4
+ const strict_typed_events_1 = require("strict-typed-events");
5
+ const common_1 = require("@opra/common");
6
+ const exception_1 = require("@opra/exception");
7
+ const i18n_1 = require("@opra/i18n");
8
+ const schema_1 = require("@opra/schema");
9
+ const index_js_1 = require("../enums/index.js");
10
+ const create_i18n_js_1 = require("../utils/create-i18n.js");
11
+ const metadata_resource_js_1 = require("./metadata-resource.js");
12
+ class OpraAdapter {
13
+ document;
14
+ i18n;
15
+ userContextResolver;
16
+ // protected _metadataResource: SingletonResourceInfo;
17
+ _internalResources = new common_1.ResponsiveMap();
18
+ constructor(document) {
19
+ this.document = document;
20
+ }
21
+ async handler(executionContext) {
22
+ let queryContexts;
23
+ let userContext;
24
+ let failed = false;
25
+ try {
26
+ queryContexts = this.prepareRequests(executionContext);
27
+ let stop = false;
28
+ // Read requests can be executed simultaneously, write request should be executed one by one
29
+ let promises;
30
+ let exclusive = false;
31
+ for (const context of queryContexts) {
32
+ exclusive = exclusive || context.query.operation !== 'read';
33
+ // Wait previous read requests before executing update request
34
+ if (exclusive && promises) {
35
+ await Promise.allSettled(promises);
36
+ promises = undefined;
37
+ }
38
+ // If previous request in bucket had an error and executed an update
39
+ // we do not execute next requests
40
+ if (stop) {
41
+ context.errors.push(new exception_1.FailedDependencyError());
42
+ continue;
43
+ }
44
+ try {
45
+ const promise = (async () => {
46
+ // if (context.query.method === 'metadata') {
47
+ // await this._getSchemaExecute(context); //todo
48
+ // return;
49
+ // }
50
+ const resource = context.query.resource;
51
+ await this._resourcePrepare(resource, context);
52
+ if (this.userContextResolver && !userContext)
53
+ userContext = this.userContextResolver({
54
+ executionContext,
55
+ isBatch: this.isBatch(executionContext)
56
+ });
57
+ context.userContext = userContext;
58
+ await this._resourceExecute(this.document, resource, context);
59
+ })().catch(e => {
60
+ context.errors.push(e);
61
+ });
62
+ if (exclusive)
63
+ await promise;
64
+ else {
65
+ promises = promises || [];
66
+ promises.push(promise);
67
+ }
68
+ // todo execute sub property queries
69
+ }
70
+ catch (e) {
71
+ context.errors.unshift(e);
72
+ }
73
+ if (context.errors.length) {
74
+ // noinspection SuspiciousTypeOfGuard
75
+ context.errors = context.errors.map(e => (0, exception_1.wrapException)(e));
76
+ if (exclusive)
77
+ stop = stop || !!context.errors.find(e => !(e.issue.severity === 'warning' || e.issue.severity === 'info'));
78
+ }
79
+ }
80
+ if (promises)
81
+ await Promise.allSettled(promises);
82
+ await this.sendResponse(executionContext, queryContexts);
83
+ }
84
+ catch (e) {
85
+ failed = true;
86
+ const error = (0, exception_1.wrapException)(e);
87
+ await this.sendError(executionContext, error);
88
+ }
89
+ finally {
90
+ if (executionContext instanceof strict_typed_events_1.AsyncEventEmitter) {
91
+ await executionContext
92
+ .emitAsyncSerial('finish', {
93
+ userContext,
94
+ failed
95
+ }).catch();
96
+ }
97
+ }
98
+ }
99
+ async _resourcePrepare(resource, context) {
100
+ const { query } = context;
101
+ const fn = resource.metadata['pre_' + query.method];
102
+ if (fn && typeof fn === 'function') {
103
+ await fn(context);
104
+ }
105
+ }
106
+ async _resourceExecute(document, resource, context) {
107
+ if (resource instanceof schema_1.CollectionResourceInfo) {
108
+ const { query } = context;
109
+ if (query.kind === 'SearchCollectionQuery') {
110
+ const promises = [];
111
+ let search;
112
+ promises.push(this._collectionResourceExecute(document, resource, context)
113
+ .then(v => search = v));
114
+ if (query.count && resource.metadata.count) {
115
+ const ctx = {
116
+ query: new schema_1.CollectionCountQuery(query.resource, { filter: query.filter }),
117
+ resultPath: ''
118
+ };
119
+ Object.setPrototypeOf(ctx, context);
120
+ promises.push(this._collectionResourceExecute(document, resource, ctx));
121
+ }
122
+ await Promise.all(promises);
123
+ context.response = search;
124
+ return;
125
+ }
126
+ context.response = await this._collectionResourceExecute(document, resource, context);
127
+ return;
128
+ }
129
+ else if (resource instanceof schema_1.SingletonResourceInfo) {
130
+ context.response = await this._singletonResourceExecute(document, resource, context);
131
+ return;
132
+ }
133
+ throw new Error(`Executing "${resource.kind}" has not been implemented yet`);
134
+ }
135
+ async _init(options) {
136
+ if (options?.i18n instanceof i18n_1.I18n)
137
+ this.i18n = options.i18n;
138
+ else if (typeof options?.i18n === 'function')
139
+ this.i18n = await options.i18n();
140
+ else
141
+ this.i18n = await (0, create_i18n_js_1.createI18n)(options?.i18n);
142
+ this.i18n = this.i18n || i18n_1.I18n.defaultInstance;
143
+ if (!this.i18n.isInitialized)
144
+ await this.i18n.init();
145
+ this.userContextResolver = options?.userContext;
146
+ const metadataResource = new metadata_resource_js_1.MetadataResource();
147
+ const metadataResourceInfo = new schema_1.SingletonResourceInfo(this.document, '$metadata', this.document.getComplexDataType('object'), {
148
+ kind: 'SingletonResource',
149
+ type: 'object',
150
+ instance: metadataResource,
151
+ get: {
152
+ handler: metadataResource.get.bind(metadataResource)
153
+ }
154
+ });
155
+ this._internalResources.set(metadataResourceInfo.name, metadataResourceInfo);
156
+ metadataResource.init(metadataResourceInfo);
157
+ for (const r of this.document.resources.values()) {
158
+ if (r.instance) {
159
+ const init = r.instance.init;
160
+ if (init)
161
+ await init.call(r.instance, r);
162
+ }
163
+ }
164
+ }
165
+ async _collectionResourceExecute(document, resource, context) {
166
+ const method = context.query.method;
167
+ const resolverInfo = resource.metadata[method];
168
+ if (!(resolverInfo && resolverInfo.handler))
169
+ throw new exception_1.ForbiddenError({
170
+ message: (0, i18n_1.translate)('RESOLVER_FORBIDDEN', { method }, `The resource endpoint does not accept '{{method}}' operations`),
171
+ severity: 'error',
172
+ code: 'RESOLVER_FORBIDDEN'
173
+ });
174
+ let result;
175
+ switch (method) {
176
+ case 'create': {
177
+ const query = context.query;
178
+ result = await resolverInfo.handler(context, query.data, query);
179
+ result = Array.isArray(result) ? result[0] : result;
180
+ if (result)
181
+ context.status = 201;
182
+ context.responseHeaders.set(index_js_1.HttpHeaders.X_Opra_DataType, resource.dataType.name);
183
+ return result;
184
+ }
185
+ case 'count': {
186
+ const query = context.query;
187
+ result = await resolverInfo.handler(context, query);
188
+ context.responseHeaders.set(index_js_1.HttpHeaders.X_Opra_Count, result);
189
+ return result;
190
+ }
191
+ case 'get': {
192
+ const query = context.query;
193
+ result = await resolverInfo.handler(context, query.keyValue, query);
194
+ result = Array.isArray(result) ? result[0] : result;
195
+ if (!result)
196
+ throw new exception_1.ResourceNotFoundError(resource.name, query.keyValue);
197
+ const v = await this._pathWalkThrough(query, query.dataType, result, resource.name);
198
+ if (v.value === undefined)
199
+ throw new exception_1.ResourceNotFoundError(v.path);
200
+ if (v.dataType)
201
+ context.responseHeaders.set(index_js_1.HttpHeaders.X_Opra_DataType, v.dataType.name);
202
+ return v.value;
203
+ }
204
+ case 'search': {
205
+ const query = context.query;
206
+ result = await resolverInfo.handler(context, query);
207
+ const items = Array.isArray(result) ? result : (context.response ? [result] : []);
208
+ context.responseHeaders.set(index_js_1.HttpHeaders.X_Opra_DataType, resource.dataType.name);
209
+ return items;
210
+ }
211
+ case 'update': {
212
+ const query = context.query;
213
+ result = await resolverInfo.handler(context, query.keyValue, query.data, query);
214
+ result = Array.isArray(result) ? result[0] : result;
215
+ if (!result)
216
+ throw new exception_1.ResourceNotFoundError(resource.name, query.keyValue);
217
+ context.responseHeaders.set(index_js_1.HttpHeaders.X_Opra_DataType, resource.dataType.name);
218
+ return result;
219
+ }
220
+ case 'delete':
221
+ case 'deleteMany':
222
+ case 'updateMany': {
223
+ switch (method) {
224
+ case 'delete': {
225
+ const query = context.query;
226
+ result = await resolverInfo.handler(context, query.keyValue, query);
227
+ break;
228
+ }
229
+ case 'deleteMany': {
230
+ const query = context.query;
231
+ result = await resolverInfo.handler(context, query);
232
+ break;
233
+ }
234
+ case 'updateMany': {
235
+ const query = context.query;
236
+ result = await resolverInfo.handler(context, query.data, query);
237
+ break;
238
+ }
239
+ }
240
+ let affected;
241
+ if (typeof result === 'number')
242
+ affected = result;
243
+ if (typeof result === 'boolean')
244
+ affected = result ? 1 : 0;
245
+ if (typeof result === 'object')
246
+ affected = result.affectedRows || result.affected;
247
+ return {
248
+ operation: context.query.method,
249
+ affected
250
+ };
251
+ }
252
+ }
253
+ }
254
+ async _singletonResourceExecute(document, resource, context) {
255
+ const method = context.query.method;
256
+ const resolverInfo = resource.metadata[method];
257
+ if (!(resolverInfo && resolverInfo.handler))
258
+ throw new exception_1.ForbiddenError({
259
+ message: (0, i18n_1.translate)('RESOLVER_FORBIDDEN', { method }, `The resource endpoint does not accept '{{method}}' operations`),
260
+ severity: 'error',
261
+ code: 'RESOLVER_FORBIDDEN'
262
+ });
263
+ let result = await resolverInfo.handler(context);
264
+ switch (method) {
265
+ case 'get': {
266
+ const query = context.query;
267
+ result = await resolverInfo.handler(context, query);
268
+ result = Array.isArray(result) ? result[0] : result;
269
+ if (!result)
270
+ throw new exception_1.ResourceNotFoundError(resource.name);
271
+ const v = await this._pathWalkThrough(query, query.dataType, result, resource.name);
272
+ if (v.value === undefined)
273
+ throw new exception_1.ResourceNotFoundError(v.path);
274
+ if (v.dataType)
275
+ context.responseHeaders.set(index_js_1.HttpHeaders.X_Opra_DataType, v.dataType.name);
276
+ return v.value;
277
+ }
278
+ }
279
+ if (!result)
280
+ return;
281
+ result = Array.isArray(result) ? result[0] : result;
282
+ let dataType = resource.dataType;
283
+ if (context.resultPath) {
284
+ const pathArray = context.resultPath.split('.');
285
+ for (const field of pathArray) {
286
+ const prop = dataType instanceof schema_1.ComplexType ? dataType.fields.get(field) : undefined;
287
+ dataType = prop && prop.type ? this.document.types.get(prop.type) : undefined;
288
+ result = result && typeof result === 'object' && result[field];
289
+ }
290
+ }
291
+ if (method === 'create')
292
+ context.status = 201;
293
+ context.responseHeaders.set(index_js_1.HttpHeaders.X_Opra_DataType, resource.dataType.name);
294
+ return result;
295
+ }
296
+ async _pathWalkThrough(query, dataType, value, parentPath) {
297
+ const { child } = query;
298
+ if (!child)
299
+ return { value, dataType, path: parentPath };
300
+ // Make a case in sensitive lookup
301
+ const fieldNameLower = child.fieldName.toLowerCase();
302
+ const path = parentPath + (parentPath ? '.' : '') + child.fieldName;
303
+ for (const key of Object.keys(value)) {
304
+ if (key.toLowerCase() === fieldNameLower) {
305
+ let v = value[key];
306
+ if (v == null)
307
+ return { path };
308
+ if (child.child && child.dataType instanceof schema_1.ComplexType) {
309
+ if (Array.isArray(v))
310
+ v = v[0];
311
+ return this._pathWalkThrough(child, child.dataType, v, path);
312
+ }
313
+ return { value: v, dataType: child.dataType, path };
314
+ }
315
+ }
316
+ return { path };
317
+ }
318
+ }
319
+ exports.OpraAdapter = OpraAdapter;
@@ -7,12 +7,9 @@ const strict_typed_events_1 = require("strict-typed-events");
7
7
  const url_1 = require("@opra/url");
8
8
  const http_adapter_js_1 = require("./http-adapter.js");
9
9
  class OpraExpressAdapter extends http_adapter_js_1.OpraHttpAdapter {
10
- static async init(app, service, options) {
11
- const i18n = await this.initI18n(options);
12
- const adapter = new OpraExpressAdapter(service, {
13
- ...options,
14
- i18n
15
- });
10
+ static async init(app, document, options) {
11
+ const adapter = new OpraExpressAdapter(document);
12
+ await adapter._init(options);
16
13
  const prefix = '/' + (0, url_1.normalizePath)(options?.prefix, true);
17
14
  app.use(prefix, body_parser_1.default.json());
18
15
  app.use(prefix, (request, response, next) => {
@@ -0,0 +1,242 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OpraHttpAdapter = void 0;
4
+ const exception_1 = require("@opra/exception");
5
+ const schema_1 = require("@opra/schema");
6
+ const url_1 = require("@opra/url");
7
+ const index_js_1 = require("../enums/index.js");
8
+ const headers_map_js_1 = require("../helpers/headers-map.js");
9
+ const adapter_js_1 = require("./adapter.js");
10
+ const query_context_js_1 = require("./query-context.js");
11
+ class OpraHttpAdapter extends adapter_js_1.OpraAdapter {
12
+ prepareRequests(executionContext) {
13
+ const req = executionContext.getRequestWrapper();
14
+ // todo implement batch requests
15
+ if (this.isBatch(executionContext)) {
16
+ throw new Error('not implemented yet');
17
+ }
18
+ const url = new url_1.OpraURL(req.getUrl());
19
+ return [
20
+ this.prepareRequest(executionContext, url, req.getMethod(), new headers_map_js_1.HeadersMap(req.getHeaders()), req.getBody())
21
+ ];
22
+ }
23
+ prepareRequest(executionContext, url, method, headers, body) {
24
+ if (!url.path.size)
25
+ throw new exception_1.BadRequestError();
26
+ if (method !== 'GET' && url.path.size > 1)
27
+ throw new exception_1.BadRequestError();
28
+ const query = this.buildQuery(url, method, body);
29
+ if (!query)
30
+ throw new exception_1.MethodNotAllowedError({
31
+ message: `Method "${method}" is not allowed by target endpoint`
32
+ });
33
+ return new query_context_js_1.QueryContext({
34
+ service: this.document,
35
+ executionContext,
36
+ query,
37
+ headers: new headers_map_js_1.HeadersMap(),
38
+ params: url.searchParams,
39
+ continueOnError: query.operation === 'read'
40
+ });
41
+ }
42
+ buildQuery(url, method, body) {
43
+ const pathLen = url.path.size;
44
+ let p = url.path.get(0);
45
+ let resource = this._internalResources.get(p.resource) || this.document.getResource(p.resource);
46
+ let container;
47
+ let pathIndex = 0;
48
+ while (resource && resource instanceof schema_1.ContainerResourceInfo) {
49
+ container = resource;
50
+ p = url.path.get(++pathIndex);
51
+ resource = container.getResource(p.resource);
52
+ }
53
+ try {
54
+ method = method.toUpperCase();
55
+ let query;
56
+ if (resource instanceof schema_1.SingletonResourceInfo && !p.key) {
57
+ switch (method) {
58
+ case 'GET': {
59
+ query = new schema_1.SingletonGetQuery(resource);
60
+ }
61
+ }
62
+ }
63
+ else if (resource instanceof schema_1.CollectionResourceInfo) {
64
+ switch (method) {
65
+ case 'GET': {
66
+ if (p.key) {
67
+ const searchParams = url.searchParams;
68
+ query = new schema_1.CollectionGetQuery(resource, p.key, {
69
+ pick: searchParams.get('$pick'),
70
+ omit: searchParams.get('$omit'),
71
+ include: searchParams.get('$include')
72
+ });
73
+ }
74
+ else {
75
+ const searchParams = url.searchParams;
76
+ query = new schema_1.CollectionSearchQuery(resource, {
77
+ filter: searchParams.get('$filter'),
78
+ limit: searchParams.get('$limit'),
79
+ skip: searchParams.get('$skip'),
80
+ distinct: searchParams.get('$distinct'),
81
+ count: searchParams.get('$count'),
82
+ sort: searchParams.get('$sort'),
83
+ pick: searchParams.get('$pick'),
84
+ omit: searchParams.get('$omit'),
85
+ include: searchParams.get('$include')
86
+ });
87
+ }
88
+ break;
89
+ }
90
+ case 'DELETE': {
91
+ const searchParams = url.searchParams;
92
+ query = p.key
93
+ ? new schema_1.CollectionDeleteQuery(resource, p.key)
94
+ : new schema_1.CollectionDeleteManyQuery(resource, {
95
+ filter: searchParams.get('$filter'),
96
+ });
97
+ break;
98
+ }
99
+ case 'POST': {
100
+ if (!p.key) {
101
+ const searchParams = url.searchParams;
102
+ query = new schema_1.CollectionCreateQuery(resource, body, {
103
+ pick: searchParams.get('$pick'),
104
+ omit: searchParams.get('$omit'),
105
+ include: searchParams.get('$include')
106
+ });
107
+ }
108
+ break;
109
+ }
110
+ case 'PATCH': {
111
+ if (p.key) {
112
+ const searchParams = url.searchParams;
113
+ query = new schema_1.CollectionUpdateQuery(resource, p.key, body, {
114
+ pick: searchParams.get('$pick'),
115
+ omit: searchParams.get('$omit'),
116
+ include: searchParams.get('$include')
117
+ });
118
+ }
119
+ else {
120
+ const searchParams = url.searchParams;
121
+ query = new schema_1.CollectionUpdateManyQuery(resource, body, {
122
+ filter: searchParams.get('$filter')
123
+ });
124
+ }
125
+ break;
126
+ }
127
+ }
128
+ }
129
+ else
130
+ throw new exception_1.InternalServerError();
131
+ if (query instanceof schema_1.SingletonGetQuery || query instanceof schema_1.CollectionGetQuery || query instanceof schema_1.FieldGetQuery) {
132
+ // Move through properties
133
+ let parentType;
134
+ const curPath = [];
135
+ let parent = query;
136
+ while (++pathIndex < pathLen) {
137
+ p = url.path.get(pathIndex);
138
+ parentType = parent.dataType;
139
+ if (parent.dataType instanceof schema_1.UnionType) {
140
+ if (parent.dataType.name === 'any')
141
+ parentType = this.document.getComplexDataType('object');
142
+ else
143
+ throw new TypeError(`"${resource.name}.${curPath.join()}" is a UnionType and needs type casting.`);
144
+ }
145
+ if (!(parentType instanceof schema_1.ComplexType))
146
+ throw new TypeError(`"${resource.name}.${curPath.join()}" is not a ComplexType and has no fields.`);
147
+ curPath.push(p.resource);
148
+ parent.child = new schema_1.FieldGetQuery(parent, p.resource, { castingType: parentType });
149
+ parent = parent.child;
150
+ }
151
+ }
152
+ return query;
153
+ }
154
+ catch (e) {
155
+ if (e instanceof exception_1.OpraException)
156
+ throw e;
157
+ throw new exception_1.BadRequestError(e);
158
+ }
159
+ }
160
+ async sendResponse(executionContext, queryContexts) {
161
+ const outputPackets = [];
162
+ for (const ctx of queryContexts) {
163
+ const v = this.createOutput(ctx);
164
+ outputPackets.push(v);
165
+ }
166
+ if (this.isBatch(executionContext)) {
167
+ // this.writeError([], new InternalServerError({message: 'Not implemented yet'}));
168
+ return;
169
+ }
170
+ if (!outputPackets.length)
171
+ return this.sendError(executionContext, new exception_1.NotFoundError());
172
+ const out = outputPackets[0];
173
+ const resp = executionContext.getResponseWrapper();
174
+ resp.setStatus(out.status);
175
+ resp.setHeader(index_js_1.HttpHeaders.Content_Type, 'application/json');
176
+ resp.setHeader(index_js_1.HttpHeaders.Cache_Control, 'no-cache');
177
+ resp.setHeader(index_js_1.HttpHeaders.Pragma, 'no-cache');
178
+ resp.setHeader(index_js_1.HttpHeaders.Expires, '-1');
179
+ resp.setHeader(index_js_1.HttpHeaders.X_Opra_Version, schema_1.OpraSchema.Version);
180
+ if (out.headers) {
181
+ for (const [k, v] of Object.entries(out.headers)) {
182
+ resp.setHeader(k, v);
183
+ }
184
+ }
185
+ resp.send(JSON.stringify(out.body));
186
+ resp.end();
187
+ }
188
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
189
+ isBatch(executionContext) {
190
+ return false;
191
+ }
192
+ createOutput(ctx) {
193
+ const { query } = ctx;
194
+ let body;
195
+ let status = ctx.status || 0;
196
+ const errors = ctx.errors.map(e => (0, exception_1.wrapException)(e));
197
+ if (errors && errors.length) {
198
+ // Sort errors from fatal to info
199
+ errors.sort((a, b) => {
200
+ const i = exception_1.IssueSeverity.Keys.indexOf(a.issue.severity) - exception_1.IssueSeverity.Keys.indexOf(b.issue.severity);
201
+ if (i === 0)
202
+ return b.status - a.status;
203
+ return i;
204
+ });
205
+ if (!status || status < index_js_1.HttpStatus.BAD_REQUEST) {
206
+ status = errors[0].status;
207
+ if (status < index_js_1.HttpStatus.BAD_REQUEST)
208
+ status = index_js_1.HttpStatus.INTERNAL_SERVER_ERROR;
209
+ }
210
+ body = {
211
+ operation: ctx.query.method,
212
+ errors: errors.map(e => e.issue)
213
+ };
214
+ }
215
+ else {
216
+ body = ctx.response;
217
+ status = status || (query.operation === 'create' ? index_js_1.HttpStatus.CREATED : index_js_1.HttpStatus.OK);
218
+ }
219
+ body = this.i18n.deep(body);
220
+ return {
221
+ status,
222
+ headers: ctx.responseHeaders.toObject(),
223
+ body
224
+ };
225
+ }
226
+ async sendError(executionContext, error) {
227
+ const resp = executionContext.getResponseWrapper();
228
+ resp.setStatus(error.status || 500);
229
+ resp.setHeader(index_js_1.HttpHeaders.Content_Type, 'application/json');
230
+ resp.setHeader(index_js_1.HttpHeaders.Cache_Control, 'no-cache');
231
+ resp.setHeader(index_js_1.HttpHeaders.Pragma, 'no-cache');
232
+ resp.setHeader(index_js_1.HttpHeaders.Expires, '-1');
233
+ resp.setHeader(index_js_1.HttpHeaders.X_Opra_Version, schema_1.OpraSchema.Version);
234
+ const issue = this.i18n.deep(error.issue);
235
+ const body = {
236
+ operation: 'unknown',
237
+ errors: [issue]
238
+ };
239
+ resp.send(JSON.stringify(body));
240
+ }
241
+ }
242
+ exports.OpraHttpAdapter = OpraHttpAdapter;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MetadataResource = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const schema_1 = require("@opra/schema");
6
+ const json_singleton_service_js_1 = require("../services/json-singleton-service.js");
7
+ let MetadataResource = class MetadataResource {
8
+ service;
9
+ init(resource) {
10
+ this.service = new json_singleton_service_js_1.JsonSingletonService(resource.dataType, {
11
+ data: resource.document.getMetadata(true)
12
+ });
13
+ }
14
+ get() {
15
+ return this.service.get();
16
+ }
17
+ };
18
+ MetadataResource = tslib_1.__decorate([
19
+ (0, schema_1.OprSingletonResource)(Object, {
20
+ name: '$metadata'
21
+ })
22
+ ], MetadataResource);
23
+ exports.MetadataResource = MetadataResource;
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.QueryContext = void 0;
4
4
  const url_1 = require("@opra/url");
5
- const headers_map_js_1 = require("./headers-map.js");
5
+ const headers_map_js_1 = require("../helpers/headers-map.js");
6
6
  class QueryContext {
7
7
  service;
8
8
  executionContext;
@@ -9,7 +9,7 @@ var HttpHeaders;
9
9
  (function (HttpHeaders) {
10
10
  /* *** Custom Headers *** */
11
11
  HttpHeaders["X_Opra_Version"] = "X-Opra-Version";
12
- HttpHeaders["X_Opra_Schema"] = "X-Opra-Schema";
12
+ HttpHeaders["X_Opra_DataType"] = "X-Opra-DataType";
13
13
  HttpHeaders["X_Opra_Count"] = "X-Opra-Count";
14
14
  /* *** Authentication *** */
15
15
  /**
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HeadersMap = void 0;
4
- const schema_1 = require("@opra/schema");
4
+ const common_1 = require("@opra/common");
5
5
  const index_js_1 = require("../enums/index.js");
6
- class HeadersMap extends schema_1.ResponsiveMap {
6
+ class HeadersMap extends common_1.ResponsiveMap {
7
7
  constructor(data) {
8
8
  super(data, Array.from(Object.values(index_js_1.HttpHeaders)));
9
9
  }
package/cjs/index.js CHANGED
@@ -5,10 +5,11 @@ require("reflect-metadata");
5
5
  tslib_1.__exportStar(require("./types.js"), exports);
6
6
  tslib_1.__exportStar(require("./enums/index.js"), exports);
7
7
  tslib_1.__exportStar(require("./interfaces/execution-context.interface.js"), exports);
8
- tslib_1.__exportStar(require("./interfaces/entity-service.interface.js"), exports);
9
- tslib_1.__exportStar(require("./implementation/query-context.js"), exports);
10
- tslib_1.__exportStar(require("./implementation/adapter.js"), exports);
11
- tslib_1.__exportStar(require("./implementation/http-adapter.js"), exports);
12
- tslib_1.__exportStar(require("./implementation/express-adapter.js"), exports);
8
+ tslib_1.__exportStar(require("./interfaces/resource.interface.js"), exports);
9
+ tslib_1.__exportStar(require("./adapter/query-context.js"), exports);
10
+ tslib_1.__exportStar(require("./adapter/adapter.js"), exports);
11
+ tslib_1.__exportStar(require("./adapter/http-adapter.js"), exports);
12
+ tslib_1.__exportStar(require("./adapter/express-adapter.js"), exports);
13
13
  tslib_1.__exportStar(require("./services/data-service.js"), exports);
14
14
  tslib_1.__exportStar(require("./services/json-collection-service.js"), exports);
15
+ tslib_1.__exportStar(require("./services/json-singleton-service.js"), exports);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });