@opra/core 0.22.0 → 0.23.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.
- package/cjs/adapter/execution-context.host.js +48 -0
- package/cjs/adapter/http/express-adapter.host.js +24 -0
- package/cjs/adapter/http/express-adapter.js +12 -45
- package/cjs/adapter/http/helpers/concat-readable.js +20 -0
- package/cjs/adapter/http/helpers/multipart-helper.js +96 -0
- package/cjs/adapter/http/helpers/query-parsers.js +16 -0
- package/cjs/adapter/http/http-adapter-base.js +127 -0
- package/cjs/adapter/http/http-adapter.host.js +57 -0
- package/cjs/adapter/http/http-adapter.js +11 -133
- package/cjs/adapter/http/{impl/http-server-request.js → http-server-request.js} +11 -5
- package/cjs/adapter/http/{impl/http-server-response.js → http-server-response.js} +4 -4
- package/cjs/adapter/http/impl/http-incoming-message.host.js +148 -0
- package/cjs/adapter/http/impl/{http-outgoing-message-host.js → http-outgoing-message.host.js} +26 -38
- package/cjs/adapter/http/request-handlers/entity-request-handler.js +378 -0
- package/cjs/adapter/http/request-handlers/request-handler-base.js +27 -0
- package/cjs/adapter/http/request-handlers/storage-request-handler.js +134 -0
- package/cjs/adapter/operation-context.js +16 -0
- package/cjs/adapter/platform-adapter.host.js +107 -0
- package/cjs/adapter/request.host.js +1 -2
- package/cjs/adapter/request.js +2 -0
- package/cjs/adapter/response.js +2 -0
- package/cjs/adapter/services/logger.js +36 -0
- package/cjs/augmentation/collection.augmentation.js +2 -0
- package/cjs/augmentation/singleton.augmentation.js +2 -0
- package/cjs/augmentation/storage.augmentation.js +2 -0
- package/cjs/index.js +15 -9
- package/esm/adapter/execution-context.host.js +44 -0
- package/esm/adapter/http/express-adapter.host.js +20 -0
- package/esm/adapter/http/express-adapter.js +11 -20
- package/esm/adapter/http/helpers/concat-readable.js +16 -0
- package/esm/adapter/http/helpers/multipart-helper.js +91 -0
- package/esm/adapter/http/helpers/query-parsers.js +12 -0
- package/esm/adapter/http/http-adapter-base.js +123 -0
- package/esm/adapter/http/http-adapter.host.js +52 -0
- package/esm/adapter/http/http-adapter.js +11 -132
- package/esm/adapter/http/{impl/http-server-request.js → http-server-request.js} +12 -6
- package/esm/adapter/http/{impl/http-server-response.js → http-server-response.js} +4 -4
- package/esm/adapter/http/impl/http-incoming-message.host.js +144 -0
- package/esm/adapter/http/impl/{http-outgoing-message-host.js → http-outgoing-message.host.js} +25 -36
- package/esm/adapter/http/request-handlers/entity-request-handler.js +373 -0
- package/esm/adapter/http/request-handlers/request-handler-base.js +23 -0
- package/esm/adapter/http/request-handlers/storage-request-handler.js +129 -0
- package/esm/adapter/operation-context.js +13 -0
- package/esm/adapter/platform-adapter.host.js +102 -0
- package/esm/adapter/request.host.js +1 -2
- package/esm/adapter/request.js +1 -0
- package/esm/adapter/response.js +1 -0
- package/esm/adapter/services/logger.js +32 -0
- package/esm/augmentation/collection.augmentation.js +1 -0
- package/esm/augmentation/singleton.augmentation.js +1 -0
- package/esm/augmentation/storage.augmentation.js +1 -0
- package/esm/index.js +15 -9
- package/i18n/en/error.json +5 -2
- package/package.json +3 -2
- package/types/adapter/execution-context.d.ts +31 -0
- package/types/adapter/execution-context.host.d.ts +27 -0
- package/types/adapter/http/express-adapter.d.ts +12 -8
- package/types/adapter/http/express-adapter.host.d.ts +11 -0
- package/types/adapter/http/helpers/concat-readable.d.ts +3 -0
- package/types/adapter/http/helpers/multipart-helper.d.ts +25 -0
- package/types/adapter/http/helpers/query-parsers.d.ts +1 -0
- package/types/adapter/http/http-adapter-base.d.ts +23 -0
- package/types/adapter/http/http-adapter.d.ts +13 -29
- package/types/adapter/http/http-adapter.host.d.ts +18 -0
- package/types/adapter/http/{impl/http-server-request.d.ts → http-server-request.d.ts} +7 -6
- package/types/adapter/http/{impl/http-server-response.d.ts → http-server-response.d.ts} +2 -2
- package/types/adapter/http/impl/{http-incoming-message-host.d.ts → http-incoming-message.host.d.ts} +16 -12
- package/types/adapter/http/impl/{http-outgoing-message-host.d.ts → http-outgoing-message.host.d.ts} +12 -16
- package/types/adapter/http/request-handlers/entity-request-handler.d.ts +24 -0
- package/types/adapter/http/request-handlers/request-handler-base.d.ts +15 -0
- package/types/adapter/http/request-handlers/storage-request-handler.d.ts +23 -0
- package/types/adapter/interfaces/logger.interface.d.ts +7 -6
- package/types/adapter/interfaces/request-handler.interface.d.ts +4 -0
- package/types/adapter/operation-context.d.ts +11 -0
- package/types/adapter/{adapter.d.ts → platform-adapter.d.ts} +18 -28
- package/types/adapter/platform-adapter.host.d.ts +31 -0
- package/types/adapter/request.d.ts +11 -0
- package/types/adapter/request.host.d.ts +12 -21
- package/types/adapter/{interfaces/response.interface.d.ts → response.d.ts} +2 -2
- package/types/adapter/response.host.d.ts +2 -2
- package/types/adapter/services/logger.d.ts +14 -0
- package/types/augmentation/collection.augmentation.d.ts +112 -0
- package/types/augmentation/singleton.augmentation.d.ts +64 -0
- package/types/augmentation/storage.augmentation.d.ts +39 -0
- package/types/index.d.ts +15 -9
- package/cjs/adapter/adapter.js +0 -118
- package/cjs/adapter/http/impl/http-incoming-message-host.js +0 -127
- package/cjs/adapter/http/request-parsers/parse-collection-request.js +0 -165
- package/cjs/adapter/http/request-parsers/parse-request.js +0 -24
- package/cjs/adapter/http/request-parsers/parse-singleton-request.js +0 -96
- package/cjs/adapter/internal/metadata.resource.js +0 -26
- package/cjs/adapter/request-context.host.js +0 -44
- package/cjs/shared/collection-resource-base.js +0 -20
- package/esm/adapter/adapter.js +0 -113
- package/esm/adapter/http/impl/http-incoming-message-host.js +0 -122
- package/esm/adapter/http/request-parsers/parse-collection-request.js +0 -161
- package/esm/adapter/http/request-parsers/parse-request.js +0 -20
- package/esm/adapter/http/request-parsers/parse-singleton-request.js +0 -92
- package/esm/adapter/internal/metadata.resource.js +0 -23
- package/esm/adapter/request-context.host.js +0 -40
- package/esm/shared/collection-resource-base.js +0 -16
- package/types/adapter/http/request-parsers/parse-collection-request.d.ts +0 -4
- package/types/adapter/http/request-parsers/parse-request.d.ts +0 -4
- package/types/adapter/http/request-parsers/parse-singleton-request.d.ts +0 -4
- package/types/adapter/interfaces/request-context.interface.d.ts +0 -31
- package/types/adapter/interfaces/request.interface.d.ts +0 -15
- package/types/adapter/internal/metadata.resource.d.ts +0 -7
- package/types/adapter/request-context.host.d.ts +0 -22
- package/types/shared/collection-resource-base.d.ts +0 -11
- /package/cjs/adapter/{interfaces/request-context.interface.js → execution-context.js} +0 -0
- /package/cjs/adapter/http/{request-parsers/batch-request-parser.js → request-handlers/parse-batch-request.js} +0 -0
- /package/cjs/adapter/interfaces/{request.interface.js → request-handler.interface.js} +0 -0
- /package/cjs/adapter/{interfaces/response.interface.js → platform-adapter.js} +0 -0
- /package/esm/adapter/{interfaces/request-context.interface.js → execution-context.js} +0 -0
- /package/esm/adapter/http/{request-parsers/batch-request-parser.js → request-handlers/parse-batch-request.js} +0 -0
- /package/esm/adapter/interfaces/{request.interface.js → request-handler.interface.js} +0 -0
- /package/esm/adapter/{interfaces/response.interface.js → platform-adapter.js} +0 -0
- /package/types/adapter/http/{request-parsers/batch-request-parser.d.ts → request-handlers/parse-batch-request.d.ts} +0 -0
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import bodyParser from 'body-parser';
|
|
2
|
+
import { toBoolean, toInt } from 'putil-varhelpers';
|
|
3
|
+
import { BadRequestError, Collection, HttpHeaderCodes, HttpStatusCodes, InternalServerError, MethodNotAllowedError, OpraException, ResourceNotFoundError, Singleton, } from '@opra/common';
|
|
4
|
+
import { OperationContext } from '../../operation-context.js';
|
|
5
|
+
import { RequestHost } from '../../request.host.js';
|
|
6
|
+
import { ResponseHost } from '../../response.host.js';
|
|
7
|
+
import { parseArrayParam } from '../helpers/query-parsers.js';
|
|
8
|
+
import { RequestHandlerBase } from './request-handler-base.js';
|
|
9
|
+
/**
|
|
10
|
+
* @class EntityRequestHandler
|
|
11
|
+
*/
|
|
12
|
+
export class EntityRequestHandler extends RequestHandlerBase {
|
|
13
|
+
constructor(adapter) {
|
|
14
|
+
super(adapter);
|
|
15
|
+
this.adapter = adapter;
|
|
16
|
+
this.bodyLoaders = new WeakMap();
|
|
17
|
+
}
|
|
18
|
+
async processRequest(executionContext) {
|
|
19
|
+
const { incoming, outgoing } = executionContext.switchToHttp();
|
|
20
|
+
// Parse incoming message and create Request object
|
|
21
|
+
const request = await this.parseRequest(incoming);
|
|
22
|
+
if (!request)
|
|
23
|
+
return;
|
|
24
|
+
const response = new ResponseHost({ http: outgoing });
|
|
25
|
+
const context = OperationContext.from(executionContext, request, response);
|
|
26
|
+
// Execute operation
|
|
27
|
+
await this.executeOperation(context);
|
|
28
|
+
if (response.errors.length) {
|
|
29
|
+
context.errors.push(...response.errors);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
await this.sendResponse(context);
|
|
33
|
+
}
|
|
34
|
+
async parseRequest(incoming) {
|
|
35
|
+
const p = incoming.parsedUrl.path[0];
|
|
36
|
+
const resource = this.adapter.api.getResource(p.resource);
|
|
37
|
+
try {
|
|
38
|
+
if (resource instanceof Collection)
|
|
39
|
+
return await this.parseCollectionRequest(resource, incoming);
|
|
40
|
+
if (resource instanceof Singleton)
|
|
41
|
+
return await this.parseSingletonRequest(resource, incoming);
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
if (e instanceof OpraException)
|
|
45
|
+
throw e;
|
|
46
|
+
throw new BadRequestError(e);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async executeOperation(context) {
|
|
50
|
+
const request = context.request;
|
|
51
|
+
const { response } = context;
|
|
52
|
+
const resource = request.resource;
|
|
53
|
+
// Call operation handler method
|
|
54
|
+
let value;
|
|
55
|
+
try {
|
|
56
|
+
value = await request.controller[request.operation].call(request.controller, context);
|
|
57
|
+
if (value == null)
|
|
58
|
+
value = response.value;
|
|
59
|
+
const { operation } = request;
|
|
60
|
+
if (operation === 'delete' || operation === 'deleteMany' || operation === 'updateMany') {
|
|
61
|
+
let affected = 0;
|
|
62
|
+
if (typeof value === 'number')
|
|
63
|
+
affected = value;
|
|
64
|
+
if (typeof value === 'boolean')
|
|
65
|
+
affected = value ? 1 : 0;
|
|
66
|
+
if (typeof value === 'object')
|
|
67
|
+
affected = value.affected || value.affectedRows ||
|
|
68
|
+
(operation === 'updateMany' ? value.updated : value.deleted);
|
|
69
|
+
response.value = affected;
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
// "get" and "update" operations must return the entity instance, otherwise it means resource not found
|
|
73
|
+
if (value == null && (request.operation === 'get' || request.operation === 'update'))
|
|
74
|
+
throw new ResourceNotFoundError(resource.name, request.key);
|
|
75
|
+
// "findMany" operation should return array of entity instances
|
|
76
|
+
if (request.operation === 'findMany')
|
|
77
|
+
value = value == null ? [] : Array.isArray(value) ? value : [value];
|
|
78
|
+
else
|
|
79
|
+
value = value == null ? {} : Array.isArray(value) ? value[0] : value;
|
|
80
|
+
response.value = value;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
response.errors.push(error);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async sendResponse(context) {
|
|
88
|
+
const { request, response } = context;
|
|
89
|
+
const resource = request.resource;
|
|
90
|
+
const outgoing = response.switchToHttp();
|
|
91
|
+
let responseObject;
|
|
92
|
+
if (request.operation === 'delete' || request.operation === 'deleteMany' || request.operation === 'updateMany') {
|
|
93
|
+
responseObject = {
|
|
94
|
+
resource: resource.name,
|
|
95
|
+
operation: request.operation,
|
|
96
|
+
affected: response.value
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
if (!response.value)
|
|
101
|
+
throw new InternalServerError(`"${request.operation}" operation should return value`);
|
|
102
|
+
const encode = resource.getEncoder(request.operation);
|
|
103
|
+
const data = encode(response.value, { coerce: true });
|
|
104
|
+
if (request.operation === 'create')
|
|
105
|
+
outgoing.statusCode = 201;
|
|
106
|
+
responseObject = {
|
|
107
|
+
resource: resource.name,
|
|
108
|
+
operation: request.operation,
|
|
109
|
+
data
|
|
110
|
+
};
|
|
111
|
+
if (request.operation === 'create' || request.operation === 'update')
|
|
112
|
+
responseObject.affected = 1;
|
|
113
|
+
if (request.operation === 'findMany' && response.count != null && response.count >= 0)
|
|
114
|
+
responseObject.totalCount = response.count;
|
|
115
|
+
}
|
|
116
|
+
outgoing.statusCode = outgoing.statusCode || HttpStatusCodes.OK;
|
|
117
|
+
const body = this.adapter._i18n.deep(responseObject);
|
|
118
|
+
outgoing.setHeader(HttpHeaderCodes.Content_Type, 'application/json; charset=utf-8');
|
|
119
|
+
outgoing.send(JSON.stringify(body));
|
|
120
|
+
outgoing.end();
|
|
121
|
+
}
|
|
122
|
+
async parseCollectionRequest(resource, incoming) {
|
|
123
|
+
if ((incoming.method === 'POST' || incoming.method === 'PATCH') &&
|
|
124
|
+
incoming.headers['content-type'] !== 'application/json')
|
|
125
|
+
throw new BadRequestError({ message: 'Unsupported Content-Type' });
|
|
126
|
+
const contentId = incoming.headers['content-id'];
|
|
127
|
+
const p = incoming.parsedUrl.path[0];
|
|
128
|
+
const params = incoming.parsedUrl.searchParams;
|
|
129
|
+
switch (incoming.method) {
|
|
130
|
+
case 'POST': {
|
|
131
|
+
if (p.key == null) {
|
|
132
|
+
const operationMeta = await this.assertOperation(resource, 'create');
|
|
133
|
+
const jsonReader = this.getBodyLoader(operationMeta);
|
|
134
|
+
const decode = resource.getDecoder('create');
|
|
135
|
+
const data = decode(await jsonReader(incoming), { coerce: true });
|
|
136
|
+
const pick = parseArrayParam(params.get('$pick'));
|
|
137
|
+
const omit = parseArrayParam(params.get('$omit'));
|
|
138
|
+
const include = parseArrayParam(params.get('$include'));
|
|
139
|
+
return new RequestHost({
|
|
140
|
+
controller: operationMeta.controller,
|
|
141
|
+
http: incoming,
|
|
142
|
+
contentId,
|
|
143
|
+
resource,
|
|
144
|
+
operation: 'create',
|
|
145
|
+
data,
|
|
146
|
+
params: {
|
|
147
|
+
pick: pick && resource.normalizeFieldPath(pick),
|
|
148
|
+
omit: omit && resource.normalizeFieldPath(omit),
|
|
149
|
+
include: include && resource.normalizeFieldPath(include)
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case 'DELETE': {
|
|
156
|
+
if (p.key != null) {
|
|
157
|
+
const operationMeta = await this.assertOperation(resource, 'delete');
|
|
158
|
+
return new RequestHost({
|
|
159
|
+
controller: operationMeta.controller,
|
|
160
|
+
http: incoming,
|
|
161
|
+
contentId,
|
|
162
|
+
resource,
|
|
163
|
+
operation: 'delete',
|
|
164
|
+
key: resource.parseKeyValue(p.key)
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
const operationMeta = await this.assertOperation(resource, 'deleteMany');
|
|
168
|
+
const filter = resource.normalizeFilter(params.get('$filter'));
|
|
169
|
+
return new RequestHost({
|
|
170
|
+
controller: operationMeta.controller,
|
|
171
|
+
http: incoming,
|
|
172
|
+
contentId,
|
|
173
|
+
resource,
|
|
174
|
+
operation: 'deleteMany',
|
|
175
|
+
params: {
|
|
176
|
+
filter
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
case 'GET': {
|
|
181
|
+
const pick = parseArrayParam(params.get('$pick'));
|
|
182
|
+
const omit = parseArrayParam(params.get('$omit'));
|
|
183
|
+
const include = parseArrayParam(params.get('$include'));
|
|
184
|
+
if (p.key != null) {
|
|
185
|
+
const operationMeta = await this.assertOperation(resource, 'get');
|
|
186
|
+
return new RequestHost({
|
|
187
|
+
controller: operationMeta.controller,
|
|
188
|
+
http: incoming,
|
|
189
|
+
contentId,
|
|
190
|
+
resource,
|
|
191
|
+
operation: 'get',
|
|
192
|
+
key: resource.parseKeyValue(p.key),
|
|
193
|
+
params: {
|
|
194
|
+
pick: pick && resource.normalizeFieldPath(pick),
|
|
195
|
+
omit: omit && resource.normalizeFieldPath(omit),
|
|
196
|
+
include: include && resource.normalizeFieldPath(include)
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
const operationMeta = await this.assertOperation(resource, 'findMany');
|
|
201
|
+
const filter = resource.normalizeFilter(params.get('$filter'));
|
|
202
|
+
const sort = parseArrayParam(params.get('$sort'));
|
|
203
|
+
return new RequestHost({
|
|
204
|
+
controller: operationMeta.controller,
|
|
205
|
+
http: incoming,
|
|
206
|
+
contentId,
|
|
207
|
+
resource,
|
|
208
|
+
operation: 'findMany',
|
|
209
|
+
params: {
|
|
210
|
+
pick: pick && resource.normalizeFieldPath(pick),
|
|
211
|
+
omit: omit && resource.normalizeFieldPath(omit),
|
|
212
|
+
include: include && resource.normalizeFieldPath(include),
|
|
213
|
+
sort: sort && resource.normalizeSortFields(sort),
|
|
214
|
+
filter,
|
|
215
|
+
limit: toInt(params.get('$limit')),
|
|
216
|
+
skip: toInt(params.get('$skip')),
|
|
217
|
+
distinct: toBoolean(params.get('$distinct')),
|
|
218
|
+
count: toBoolean(params.get('$count')),
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
case 'PATCH': {
|
|
223
|
+
if (p.key != null) {
|
|
224
|
+
const operationMeta = await this.assertOperation(resource, 'update');
|
|
225
|
+
const jsonReader = this.getBodyLoader(operationMeta);
|
|
226
|
+
const decode = resource.getDecoder('update');
|
|
227
|
+
const data = decode(await jsonReader(incoming), { coerce: true });
|
|
228
|
+
const pick = parseArrayParam(params.get('$pick'));
|
|
229
|
+
const omit = parseArrayParam(params.get('$omit'));
|
|
230
|
+
const include = parseArrayParam(params.get('$include'));
|
|
231
|
+
return new RequestHost({
|
|
232
|
+
controller: operationMeta.controller,
|
|
233
|
+
http: incoming,
|
|
234
|
+
contentId,
|
|
235
|
+
resource,
|
|
236
|
+
operation: 'update',
|
|
237
|
+
key: resource.parseKeyValue(p.key),
|
|
238
|
+
data,
|
|
239
|
+
params: {
|
|
240
|
+
pick: pick && resource.normalizeFieldPath(pick),
|
|
241
|
+
omit: omit && resource.normalizeFieldPath(omit),
|
|
242
|
+
include: include && resource.normalizeFieldPath(include),
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
const operationMeta = await this.assertOperation(resource, 'updateMany');
|
|
247
|
+
const jsonReader = this.getBodyLoader(operationMeta);
|
|
248
|
+
const decode = resource.getDecoder('updateMany');
|
|
249
|
+
const data = decode(await jsonReader(incoming), { coerce: true });
|
|
250
|
+
const filter = resource.normalizeFilter(params.get('$filter'));
|
|
251
|
+
return new RequestHost({
|
|
252
|
+
controller: operationMeta.controller,
|
|
253
|
+
http: incoming,
|
|
254
|
+
contentId,
|
|
255
|
+
resource,
|
|
256
|
+
operation: 'updateMany',
|
|
257
|
+
data,
|
|
258
|
+
params: {
|
|
259
|
+
filter,
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
throw new MethodNotAllowedError({
|
|
265
|
+
message: `Collection resources do not accept http "${incoming.method}" method`
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
async parseSingletonRequest(resource, incoming) {
|
|
269
|
+
if ((incoming.method === 'POST' || incoming.method === 'PATCH') &&
|
|
270
|
+
incoming.headers['content-type'] !== 'application/json')
|
|
271
|
+
throw new BadRequestError({ message: 'Unsupported Content-Type' });
|
|
272
|
+
const contentId = incoming.headers['content-id'];
|
|
273
|
+
const params = incoming.parsedUrl.searchParams;
|
|
274
|
+
switch (incoming.method) {
|
|
275
|
+
case 'POST': {
|
|
276
|
+
const operationMeta = await this.assertOperation(resource, 'create');
|
|
277
|
+
const jsonReader = this.getBodyLoader(operationMeta);
|
|
278
|
+
const decode = resource.getDecoder('create');
|
|
279
|
+
const data = decode(await jsonReader(incoming), { coerce: true });
|
|
280
|
+
const pick = parseArrayParam(params.get('$pick'));
|
|
281
|
+
const omit = parseArrayParam(params.get('$omit'));
|
|
282
|
+
const include = parseArrayParam(params.get('$include'));
|
|
283
|
+
return new RequestHost({
|
|
284
|
+
controller: operationMeta.controller,
|
|
285
|
+
http: incoming,
|
|
286
|
+
contentId,
|
|
287
|
+
resource,
|
|
288
|
+
operation: 'create',
|
|
289
|
+
data,
|
|
290
|
+
params: {
|
|
291
|
+
pick: pick && resource.normalizeFieldPath(pick),
|
|
292
|
+
omit: omit && resource.normalizeFieldPath(omit),
|
|
293
|
+
include: include && resource.normalizeFieldPath(include)
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
case 'DELETE': {
|
|
298
|
+
const operationMeta = await this.assertOperation(resource, 'delete');
|
|
299
|
+
return new RequestHost({
|
|
300
|
+
controller: operationMeta.controller,
|
|
301
|
+
http: incoming,
|
|
302
|
+
contentId,
|
|
303
|
+
resource,
|
|
304
|
+
operation: 'delete',
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
case 'GET': {
|
|
308
|
+
const operationMeta = await this.assertOperation(resource, 'get');
|
|
309
|
+
const pick = parseArrayParam(params.get('$pick'));
|
|
310
|
+
const omit = parseArrayParam(params.get('$omit'));
|
|
311
|
+
const include = parseArrayParam(params.get('$include'));
|
|
312
|
+
return new RequestHost({
|
|
313
|
+
controller: operationMeta.controller,
|
|
314
|
+
http: incoming,
|
|
315
|
+
contentId,
|
|
316
|
+
resource,
|
|
317
|
+
operation: 'get',
|
|
318
|
+
params: {
|
|
319
|
+
pick: pick && resource.normalizeFieldPath(pick),
|
|
320
|
+
omit: omit && resource.normalizeFieldPath(omit),
|
|
321
|
+
include: include && resource.normalizeFieldPath(include)
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
case 'PATCH': {
|
|
326
|
+
const operationMeta = await this.assertOperation(resource, 'update');
|
|
327
|
+
const jsonReader = this.getBodyLoader(operationMeta);
|
|
328
|
+
const decode = resource.getDecoder('update');
|
|
329
|
+
const data = decode(await jsonReader(incoming), { coerce: true });
|
|
330
|
+
const pick = parseArrayParam(params.get('$pick'));
|
|
331
|
+
const omit = parseArrayParam(params.get('$omit'));
|
|
332
|
+
const include = parseArrayParam(params.get('$include'));
|
|
333
|
+
return new RequestHost({
|
|
334
|
+
controller: operationMeta.controller,
|
|
335
|
+
http: incoming,
|
|
336
|
+
contentId,
|
|
337
|
+
resource,
|
|
338
|
+
operation: 'update',
|
|
339
|
+
data,
|
|
340
|
+
params: {
|
|
341
|
+
pick: pick && resource.normalizeFieldPath(pick),
|
|
342
|
+
omit: omit && resource.normalizeFieldPath(omit),
|
|
343
|
+
include: include && resource.normalizeFieldPath(include),
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
throw new MethodNotAllowedError({
|
|
349
|
+
message: `Singleton resources do not accept http "${incoming.method}" method`
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
getBodyLoader(operation) {
|
|
353
|
+
let bodyLoader = this.bodyLoaders.get(operation);
|
|
354
|
+
if (!bodyLoader) {
|
|
355
|
+
const parser = bodyParser.json({
|
|
356
|
+
limit: operation.input?.maxContentSize,
|
|
357
|
+
type: 'json'
|
|
358
|
+
});
|
|
359
|
+
bodyLoader = (incoming) => {
|
|
360
|
+
return new Promise((resolve, reject) => {
|
|
361
|
+
const next = (error) => {
|
|
362
|
+
if (error)
|
|
363
|
+
return reject(error);
|
|
364
|
+
resolve(incoming.body);
|
|
365
|
+
};
|
|
366
|
+
parser(incoming, {}, next);
|
|
367
|
+
});
|
|
368
|
+
};
|
|
369
|
+
this.bodyLoaders.set(operation, bodyLoader);
|
|
370
|
+
}
|
|
371
|
+
return bodyLoader;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ForbiddenError, translate } from '@opra/common';
|
|
2
|
+
/**
|
|
3
|
+
* @class RequestHandlerBase
|
|
4
|
+
*/
|
|
5
|
+
export class RequestHandlerBase {
|
|
6
|
+
constructor(adapter) {
|
|
7
|
+
this.adapter = adapter;
|
|
8
|
+
}
|
|
9
|
+
async assertOperation(resource, operation) {
|
|
10
|
+
const controller = await this.adapter.getController(resource);
|
|
11
|
+
const operationMeta = (typeof controller?.[operation] === 'function') && resource.operations[operation];
|
|
12
|
+
if (operationMeta)
|
|
13
|
+
return {
|
|
14
|
+
...operationMeta,
|
|
15
|
+
controller
|
|
16
|
+
};
|
|
17
|
+
throw new ForbiddenError({
|
|
18
|
+
message: translate('RESOLVER_FORBIDDEN', { resource: resource.name, operation }, `'{{resource}}' endpoint does not accept '{{operation}}' operations`),
|
|
19
|
+
severity: 'error',
|
|
20
|
+
code: 'RESOLVER_FORBIDDEN'
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import fs from 'fs/promises';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import { BadRequestError, HttpStatusCodes, isReadable, OpraException, Storage, uid } from '@opra/common';
|
|
4
|
+
import { OperationContext } from '../../operation-context.js';
|
|
5
|
+
import { RequestHost } from '../../request.host.js';
|
|
6
|
+
import { ResponseHost } from '../../response.host.js';
|
|
7
|
+
import { MultipartIterator } from '../helpers/multipart-helper.js';
|
|
8
|
+
import { RequestHandlerBase } from './request-handler-base.js';
|
|
9
|
+
/**
|
|
10
|
+
* @class StorageRequestHandler
|
|
11
|
+
*/
|
|
12
|
+
export class StorageRequestHandler extends RequestHandlerBase {
|
|
13
|
+
constructor(adapter, options) {
|
|
14
|
+
super(adapter);
|
|
15
|
+
this.adapter = adapter;
|
|
16
|
+
this._uploadDir = options?.uploadDir || os.tmpdir();
|
|
17
|
+
}
|
|
18
|
+
async processRequest(executionContext) {
|
|
19
|
+
const { incoming, outgoing } = executionContext.switchToHttp();
|
|
20
|
+
// Parse incoming message and create Request object
|
|
21
|
+
const request = await this.parseRequest(executionContext, incoming);
|
|
22
|
+
if (!request)
|
|
23
|
+
return;
|
|
24
|
+
const response = new ResponseHost({ http: outgoing });
|
|
25
|
+
const context = OperationContext.from(executionContext, request, response);
|
|
26
|
+
// Execute operation
|
|
27
|
+
await this.executeOperation(context);
|
|
28
|
+
if (response.errors.length) {
|
|
29
|
+
context.errors.push(...response.errors);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
await this.sendResponse(context);
|
|
33
|
+
}
|
|
34
|
+
async parseRequest(executionContext, incoming) {
|
|
35
|
+
const contentId = incoming.headers['content-id'];
|
|
36
|
+
const p = incoming.parsedUrl.path[0];
|
|
37
|
+
const resource = this.adapter.api.getResource(p.resource);
|
|
38
|
+
try {
|
|
39
|
+
if (!(resource instanceof Storage))
|
|
40
|
+
return;
|
|
41
|
+
switch (incoming.method) {
|
|
42
|
+
case 'GET': {
|
|
43
|
+
const operationMeta = await this.assertOperation(resource, 'get');
|
|
44
|
+
return new RequestHost({
|
|
45
|
+
controller: operationMeta.controller,
|
|
46
|
+
http: incoming,
|
|
47
|
+
resource,
|
|
48
|
+
operation: 'get',
|
|
49
|
+
contentId
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
case 'DELETE': {
|
|
53
|
+
const operationMeta = await this.assertOperation(resource, 'delete');
|
|
54
|
+
return new RequestHost({
|
|
55
|
+
controller: operationMeta.controller,
|
|
56
|
+
http: incoming,
|
|
57
|
+
resource,
|
|
58
|
+
operation: 'delete',
|
|
59
|
+
contentId
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
case 'POST': {
|
|
63
|
+
const operationMeta = await this.assertOperation(resource, 'post');
|
|
64
|
+
await fs.mkdir(this._uploadDir, { recursive: true });
|
|
65
|
+
const multipartIterator = new MultipartIterator(incoming, {
|
|
66
|
+
...operationMeta,
|
|
67
|
+
filename: () => this.adapter.serviceName + '_p' + process.pid +
|
|
68
|
+
't' + String(Date.now()).substring(8) + 'r' + uid(12)
|
|
69
|
+
});
|
|
70
|
+
multipartIterator.pause();
|
|
71
|
+
// Add an hook to clean up files after request finished
|
|
72
|
+
executionContext.on('finish', async () => {
|
|
73
|
+
multipartIterator.cancel();
|
|
74
|
+
await multipartIterator.deleteFiles().catch(() => void 0);
|
|
75
|
+
});
|
|
76
|
+
return new RequestHost({
|
|
77
|
+
controller: operationMeta.controller,
|
|
78
|
+
http: incoming,
|
|
79
|
+
resource,
|
|
80
|
+
operation: 'post',
|
|
81
|
+
contentId,
|
|
82
|
+
parts: multipartIterator
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
if (e instanceof OpraException)
|
|
89
|
+
throw e;
|
|
90
|
+
throw new BadRequestError(e);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async executeOperation(context) {
|
|
94
|
+
const request = context.request;
|
|
95
|
+
const { response } = context;
|
|
96
|
+
// Call operation handler method
|
|
97
|
+
let value;
|
|
98
|
+
try {
|
|
99
|
+
value = await request.controller[request.operation].call(request.controller, context);
|
|
100
|
+
if (response.value == null)
|
|
101
|
+
response.value = value;
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
response.errors.push(error);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async sendResponse(context) {
|
|
108
|
+
const { response } = context;
|
|
109
|
+
const outgoing = response.switchToHttp();
|
|
110
|
+
outgoing.statusCode = outgoing.statusCode || HttpStatusCodes.OK;
|
|
111
|
+
if (response.value != null) {
|
|
112
|
+
if (typeof response.value === 'string') {
|
|
113
|
+
if (!outgoing.hasHeader('content-type'))
|
|
114
|
+
outgoing.setHeader('content-type', 'text/plain');
|
|
115
|
+
outgoing.send(response.value);
|
|
116
|
+
}
|
|
117
|
+
else if (Buffer.isBuffer(response.value) || isReadable(response.value)) {
|
|
118
|
+
if (!outgoing.hasHeader('content-type'))
|
|
119
|
+
outgoing.setHeader('content-type', 'application/octet-stream');
|
|
120
|
+
outgoing.send(response.value);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
outgoing.setHeader('content-type', 'application/json; charset=utf-8');
|
|
124
|
+
outgoing.send(JSON.stringify(response.value));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
outgoing.end();
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export var OperationContext;
|
|
2
|
+
(function (OperationContext) {
|
|
3
|
+
function from(executionContext, request, response) {
|
|
4
|
+
const out = {
|
|
5
|
+
request,
|
|
6
|
+
response,
|
|
7
|
+
requestScope: {}
|
|
8
|
+
};
|
|
9
|
+
Object.setPrototypeOf(out, executionContext);
|
|
10
|
+
return out;
|
|
11
|
+
}
|
|
12
|
+
OperationContext.from = from;
|
|
13
|
+
})(OperationContext || (OperationContext = {}));
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import { pascalCase } from 'putil-varhelpers';
|
|
3
|
+
import { AsyncEventEmitter } from 'strict-typed-events';
|
|
4
|
+
import { getStackFileName, I18n, Resource } from '@opra/common';
|
|
5
|
+
import { Logger } from './services/logger.js';
|
|
6
|
+
/**
|
|
7
|
+
* @class PlatformAdapterHost
|
|
8
|
+
*/
|
|
9
|
+
export class PlatformAdapterHost extends AsyncEventEmitter {
|
|
10
|
+
constructor(api, options) {
|
|
11
|
+
super();
|
|
12
|
+
this.api = api;
|
|
13
|
+
this._controllers = new WeakMap();
|
|
14
|
+
this._initialized = false;
|
|
15
|
+
this._options = options || {};
|
|
16
|
+
this._logger = options?.logger && options.logger instanceof Logger
|
|
17
|
+
? options.logger
|
|
18
|
+
: new Logger({ instance: options?.logger });
|
|
19
|
+
// Assign events
|
|
20
|
+
if (options?.on) {
|
|
21
|
+
for (const [event, fn] of Object.entries(options.on)) {
|
|
22
|
+
/* istanbul ignore next */
|
|
23
|
+
if (typeof fn === 'function')
|
|
24
|
+
this.on(event, fn);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
// Make a safe service name
|
|
28
|
+
this._serviceName = pascalCase((api.info.title || '').replace(/[^a-z0-9_ ]/ig, '')) || 'OpraService';
|
|
29
|
+
if (!/^[a-z]/i.test(this._serviceName))
|
|
30
|
+
this._serviceName = 'X' + this._serviceName;
|
|
31
|
+
}
|
|
32
|
+
get platform() {
|
|
33
|
+
return this._platform;
|
|
34
|
+
}
|
|
35
|
+
get protocol() {
|
|
36
|
+
return this._protocol;
|
|
37
|
+
}
|
|
38
|
+
get serviceName() {
|
|
39
|
+
return this.api.info.title;
|
|
40
|
+
}
|
|
41
|
+
async close() {
|
|
42
|
+
const promises = [];
|
|
43
|
+
for (const r of this.api.resources.values()) {
|
|
44
|
+
const onShutdown = r.onShutdown;
|
|
45
|
+
if (onShutdown)
|
|
46
|
+
promises.push((async () => onShutdown.call(r.controller, r))());
|
|
47
|
+
}
|
|
48
|
+
await Promise.allSettled(promises);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Initializes the adapter
|
|
52
|
+
*/
|
|
53
|
+
async init() {
|
|
54
|
+
if (this._initialized)
|
|
55
|
+
return;
|
|
56
|
+
// Init I18n
|
|
57
|
+
if (this._options?.i18n instanceof I18n)
|
|
58
|
+
this._i18n = this._options.i18n;
|
|
59
|
+
else if (typeof this._options?.i18n === 'function')
|
|
60
|
+
this._i18n = await this._options.i18n();
|
|
61
|
+
else
|
|
62
|
+
this._i18n = await this._createI18n(this._options?.i18n);
|
|
63
|
+
this._i18n = this._i18n || I18n.defaultInstance;
|
|
64
|
+
if (!this._i18n.isInitialized)
|
|
65
|
+
await this._i18n.init();
|
|
66
|
+
// Initialize all controllers
|
|
67
|
+
for (const resource of this.api.resources.values()) {
|
|
68
|
+
await this.getController(resource);
|
|
69
|
+
}
|
|
70
|
+
this._initialized = true;
|
|
71
|
+
}
|
|
72
|
+
async getController(resource) {
|
|
73
|
+
resource = typeof resource === 'object' && resource instanceof Resource
|
|
74
|
+
? resource : this.api.getResource(resource);
|
|
75
|
+
let controller = this._controllers.get(resource);
|
|
76
|
+
if (!controller) {
|
|
77
|
+
if (resource.controller) {
|
|
78
|
+
controller = typeof resource.controller === 'function' ?
|
|
79
|
+
new resource.controller()
|
|
80
|
+
: resource.controller;
|
|
81
|
+
// Initialize controller
|
|
82
|
+
if (typeof controller.onInit === 'function')
|
|
83
|
+
await controller.onInit.call(controller);
|
|
84
|
+
this._controllers.set(resource, controller);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return controller;
|
|
88
|
+
}
|
|
89
|
+
async _createI18n(options) {
|
|
90
|
+
const opts = {
|
|
91
|
+
...options,
|
|
92
|
+
};
|
|
93
|
+
delete opts.resourceDirs;
|
|
94
|
+
const instance = I18n.createInstance(opts);
|
|
95
|
+
await instance.init();
|
|
96
|
+
await instance.loadResourceDir(path.resolve(getStackFileName(), '../../../i18n'));
|
|
97
|
+
if (options?.resourceDirs)
|
|
98
|
+
for (const dir of options.resourceDirs)
|
|
99
|
+
await instance.loadResourceDir(dir);
|
|
100
|
+
return instance;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|