@atscript/odata-client 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +398 -2
- package/dist/index.cjs +1948 -0
- package/dist/index.d.cts +573 -0
- package/dist/index.d.mts +573 -0
- package/dist/index.mjs +1940 -0
- package/package.json +61 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1948 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _atscript_db_client = require("@atscript/db-client");
|
|
3
|
+
let _atscript_odata = require("@atscript/odata");
|
|
4
|
+
let _atscript_typescript_utils = require("@atscript/typescript/utils");
|
|
5
|
+
let _atscript_db_meta = require("@atscript/db/meta");
|
|
6
|
+
//#region src/errors.ts
|
|
7
|
+
function body(statusCode, message, code, errors) {
|
|
8
|
+
return code === void 0 ? {
|
|
9
|
+
message,
|
|
10
|
+
statusCode,
|
|
11
|
+
errors
|
|
12
|
+
} : {
|
|
13
|
+
message,
|
|
14
|
+
statusCode,
|
|
15
|
+
code,
|
|
16
|
+
errors
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/** The error of an operation the client does not implement yet: `400`, `NOT_SUPPORTED`. */
|
|
20
|
+
function unsupportedOperation(operation, entitySet) {
|
|
21
|
+
return new _atscript_db_client.ClientError(400, body(400, `"${operation}" is not supported on the OData entity set "${entitySet}" yet`, "NOT_SUPPORTED", []));
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A write the client refuses before any call, as a Moost server refuses what it cannot write:
|
|
25
|
+
* `400` `NOT_SUPPORTED`, one entry at `path` carrying the specific `code`.
|
|
26
|
+
*/
|
|
27
|
+
function writeRefused(code, path, message) {
|
|
28
|
+
return new _atscript_db_client.ClientError(400, body(400, message, "NOT_SUPPORTED", [{
|
|
29
|
+
path,
|
|
30
|
+
message,
|
|
31
|
+
code
|
|
32
|
+
}]));
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* What moost-db answers for a row that does not exist, or a table it refuses (`notFoundError()`):
|
|
36
|
+
* `404`, `{ message: "Not found", statusCode: 404, code: "NOT_FOUND" }`.
|
|
37
|
+
*/
|
|
38
|
+
function notFound() {
|
|
39
|
+
return new _atscript_db_client.ClientError(404, {
|
|
40
|
+
message: "Not found",
|
|
41
|
+
statusCode: 404,
|
|
42
|
+
code: "NOT_FOUND"
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* What `@atscript/db-client` throws for moost-db's answer to a write with a stale version token:
|
|
47
|
+
* a `VersionMismatchError` with moost-db's body (`409`, `code: "VERSION_MISMATCH"`,
|
|
48
|
+
* `kind: "version_mismatch"`, the entity's current token as `currentVersion` and in `params`).
|
|
49
|
+
*/
|
|
50
|
+
function versionMismatch(currentVersion) {
|
|
51
|
+
return new _atscript_db_client.VersionMismatchError(409, {
|
|
52
|
+
message: "version_mismatch",
|
|
53
|
+
statusCode: 409,
|
|
54
|
+
code: "VERSION_MISMATCH",
|
|
55
|
+
params: currentVersion === void 0 ? {} : { currentVersion },
|
|
56
|
+
kind: "version_mismatch",
|
|
57
|
+
...currentVersion === void 0 ? {} : { currentVersion }
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* What db-client's preflight throws for a payload its type rejects, from the validator's error of
|
|
62
|
+
* an operation's parameters: a `ClientValidationError` (400) with one entry per message, the
|
|
63
|
+
* path, the message, and the code and `params` where the validator gave them.
|
|
64
|
+
*/
|
|
65
|
+
function validationError(error) {
|
|
66
|
+
return new _atscript_db_client.ClientValidationError(error.errors.map(({ path, message, code, params }) => {
|
|
67
|
+
const entry = {
|
|
68
|
+
path,
|
|
69
|
+
message
|
|
70
|
+
};
|
|
71
|
+
if (code !== void 0) entry.code = code;
|
|
72
|
+
if (params !== void 0) entry.params = params;
|
|
73
|
+
return entry;
|
|
74
|
+
}));
|
|
75
|
+
}
|
|
76
|
+
/** `entries` with `[index]` in front of every path, as db-client words the rows of an array. */
|
|
77
|
+
function indexed(entries, index) {
|
|
78
|
+
return entries.map((entry) => ({
|
|
79
|
+
...entry,
|
|
80
|
+
path: entry.path ? `[${index}].${entry.path}` : `[${index}]`
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The error of row `index` of an array write: the paths of a `ClientError` gain the row's index
|
|
85
|
+
* (`[2].Country`), as db-client's preflight reports them, its `cause` kept. Anything else comes
|
|
86
|
+
* back unchanged.
|
|
87
|
+
*/
|
|
88
|
+
function atRow(error, index) {
|
|
89
|
+
if (!(error instanceof _atscript_db_client.ClientError)) return error;
|
|
90
|
+
const errors = indexed(error.errors, index);
|
|
91
|
+
if (error instanceof _atscript_db_client.ClientValidationError) return causedAs(new _atscript_db_client.ClientValidationError(errors), error);
|
|
92
|
+
if (error instanceof _atscript_db_client.VersionMismatchError) return causedAs(new _atscript_db_client.VersionMismatchError(error.status, {
|
|
93
|
+
...error.body,
|
|
94
|
+
errors
|
|
95
|
+
}), error);
|
|
96
|
+
return causedAs(new _atscript_db_client.ClientError(error.status, {
|
|
97
|
+
...error.body,
|
|
98
|
+
errors
|
|
99
|
+
}), error);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* The error of a request on several rows where rows failed (an operation on rows, an array
|
|
103
|
+
* insert), as a Moost server answers it: the first failed row's error (its class, status and
|
|
104
|
+
* code), its message and entries those of `rowsFailure` of `@atscript/odata` (every failed row's
|
|
105
|
+
* entries at that row, `[i]`, `[i].Note`, and an `INSERTED` entry for each row `created`). Anything
|
|
106
|
+
* but `ClientError`s: the first failed row's error.
|
|
107
|
+
*
|
|
108
|
+
* @param total how many rows the request held
|
|
109
|
+
*/
|
|
110
|
+
function rowsFailed(total, failed, created = []) {
|
|
111
|
+
const first = failed[0].error;
|
|
112
|
+
if (!failed.every(({ error }) => error instanceof _atscript_db_client.ClientError)) return first;
|
|
113
|
+
const { message, entries } = (0, _atscript_odata.rowsFailure)(total, failed.map(({ index, error }) => {
|
|
114
|
+
const { body, errors } = error;
|
|
115
|
+
const { code, params } = body;
|
|
116
|
+
return {
|
|
117
|
+
index,
|
|
118
|
+
message: body.message,
|
|
119
|
+
entries: errors,
|
|
120
|
+
...code === void 0 ? {} : { code },
|
|
121
|
+
...params === void 0 ? {} : { params }
|
|
122
|
+
};
|
|
123
|
+
}), created);
|
|
124
|
+
const { status, body } = first;
|
|
125
|
+
const answer = {
|
|
126
|
+
...body,
|
|
127
|
+
message,
|
|
128
|
+
errors: entries
|
|
129
|
+
};
|
|
130
|
+
return causedAs(first instanceof _atscript_db_client.VersionMismatchError ? new _atscript_db_client.VersionMismatchError(status, answer) : new _atscript_db_client.ClientError(status, answer), first);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Maps the target of a service message to a field path of the entity set: `@atscript/odata`'s
|
|
134
|
+
* `messagePath`, the rule both hosts use. `CompanyCode`, `/OrderSet('1')/NetAmount`,
|
|
135
|
+
* `Items(ItemNo='10')/Quantity` and `_it/Address/City` become `CompanyCode`, `NetAmount`,
|
|
136
|
+
* `Items.Quantity` and `Address.City`; a target that names no property of the entity type, and a
|
|
137
|
+
* pseudo target like `/#TRANSIENT#`, yield `""`.
|
|
138
|
+
*/
|
|
139
|
+
function messagePath(target, context = {}) {
|
|
140
|
+
return (0, _atscript_odata.messagePath)(target, context);
|
|
141
|
+
}
|
|
142
|
+
/** A cause db-client's `TransportError.aborted` recognizes. */
|
|
143
|
+
function abortCause(error) {
|
|
144
|
+
const name = error.cause?.name;
|
|
145
|
+
if (name === "AbortError" || name === "TimeoutError") return error.cause;
|
|
146
|
+
const cause = new Error(error.message, { cause: error.cause ?? error });
|
|
147
|
+
cause.name = /timed out/i.test(error.message) ? "TimeoutError" : "AbortError";
|
|
148
|
+
return cause;
|
|
149
|
+
}
|
|
150
|
+
function isPage(error) {
|
|
151
|
+
const type = error.headers["content-type"] ?? "";
|
|
152
|
+
return /html/i.test(type) || typeof error.body === "string" && /^\uFEFF?\s*<(?:!doctype\s+html|html[\s>])/i.test(error.body);
|
|
153
|
+
}
|
|
154
|
+
function fromODataError(error, context) {
|
|
155
|
+
const { method, url } = error.request;
|
|
156
|
+
switch (error.kind) {
|
|
157
|
+
case "network": return new _atscript_db_client.TransportError(method, url, error.message, error.cause ?? error);
|
|
158
|
+
case "aborted": return new _atscript_db_client.TransportError(method, url, error.message, abortCause(error));
|
|
159
|
+
case "unexpected-content": return isPage(error) ? new _atscript_db_client.ClientError(401, body(401, error.message, "UNEXPECTED_CONTENT", [])) : new _atscript_db_client.TransportError(method, url, error.message, error);
|
|
160
|
+
default: return new _atscript_db_client.ClientError(error.status, body(error.status, error.message, error.code, (0, _atscript_odata.messageEntries)(error, context)));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* `client` with the engine's error as its `cause`, as a server's `DbError` carries it: not
|
|
165
|
+
* enumerable, so the error's body and its JSON stay what a Moost server answers.
|
|
166
|
+
*/
|
|
167
|
+
function withCause(client, cause) {
|
|
168
|
+
Object.defineProperty(client, "cause", {
|
|
169
|
+
value: cause,
|
|
170
|
+
enumerable: false,
|
|
171
|
+
writable: true,
|
|
172
|
+
configurable: true
|
|
173
|
+
});
|
|
174
|
+
return client;
|
|
175
|
+
}
|
|
176
|
+
/** `client`, a copy of `error` (a row's error re-worded), with the `cause` `error` carries. */
|
|
177
|
+
function causedAs(client, error) {
|
|
178
|
+
return Object.hasOwn(error, "cause") ? withCause(client, error.cause) : client;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Turns what the OData engine throws into what `@atscript/db-client` throws, so an application
|
|
182
|
+
* handles both backends with one `instanceof ClientError` / `instanceof TransportError` branch.
|
|
183
|
+
* The error to throw is returned; an error that is already one of db-client's, and any error this
|
|
184
|
+
* package does not know, comes back unchanged.
|
|
185
|
+
*
|
|
186
|
+
* A failure a Moost server answers with a `DbError` (`dbFailureOf` of `@atscript/odata`, the one
|
|
187
|
+
* mapping both hosts use) is the `ClientError` a Moost server's answer becomes: the status
|
|
188
|
+
* moost-db answers the code with and its body (`message`, `statusCode`, `code`, `errors`). The
|
|
189
|
+
* engine's error is its `cause` (not enumerable, outside the body): what the service said behind
|
|
190
|
+
* a generic `STORE_*` message.
|
|
191
|
+
*
|
|
192
|
+
* | Thrown by the engine | Result |
|
|
193
|
+
* | -------------------------------------------------------------- | ------------------------------------------------------------------------- |
|
|
194
|
+
* | `ODataQueryError` `UNSUPPORTED_AGGREGATE`, `UNSUPPORTED_ON_V2` | `ClientError` 400, `NOT_SUPPORTED` |
|
|
195
|
+
* | `ODataWriteError` of `writeRefusal` (`NOT_INSERTABLE`, …) | `ClientError` 400, `NOT_SUPPORTED` |
|
|
196
|
+
* | `ODataQueryError` (other) | `ClientError` 400, `INVALID_QUERY`; `UNKNOWN_FIELD`, … on the entry |
|
|
197
|
+
* | `ODataWriteError` (other) | `ClientError` 400, `INVALID_QUERY`; the engine's code on the entry |
|
|
198
|
+
* | `ODataValueError` | `ClientError` 400, `INVALID_QUERY`, the property |
|
|
199
|
+
* | `ODataServiceError` `PAGE_LIMIT` | `ClientError` 400, `INVALID_QUERY` on `$limit` |
|
|
200
|
+
* | `ODataError` `400` | `ClientError` 400, `INVALID_QUERY`, the service's messages by field |
|
|
201
|
+
* | `ODataError` `409` | `ClientError` 409, `CONFLICT`, as for `400` |
|
|
202
|
+
* | `ODataError` `501` | `ClientError` 400, `NOT_SUPPORTED`, the service's messages by field |
|
|
203
|
+
* | `ODataError` `412` (the last attempt of a last-write-wins write) | `ClientError` 503, `SERIALIZATION_FAILURE` |
|
|
204
|
+
* | `ODataError` `429` | `ClientError` 429, `STORE_THROTTLED`, `params.retryAfter` on the entry |
|
|
205
|
+
* | `ODataError` `504` | `ClientError` 504, `STORE_TIMEOUT` |
|
|
206
|
+
* | `ODataError` `5xx` (other than `501`) | `ClientError` 502, `STORE_FAILED` |
|
|
207
|
+
* | `ODataError` `http` / `csrf` (other) | `ClientError` with the HTTP status, the service's code and messages |
|
|
208
|
+
* | `ODataError` `unexpected-content`, an HTML page | `ClientError` 401, `UNEXPECTED_CONTENT` |
|
|
209
|
+
* | `ODataError` `unexpected-content`, otherwise | `TransportError`: a `2xx` answer that cannot be read |
|
|
210
|
+
* | `ODataError` `network` / `aborted` | `TransportError` (`aborted` is `true` for an aborted call) |
|
|
211
|
+
* | `ODataServiceError` (other), an unreadable body | `TransportError`: the service answered, the answer is not usable |
|
|
212
|
+
* | `ValidatorError` (an operation's parameters, `runOperation`) | `ClientValidationError` (400): the validator's entries, nothing sent |
|
|
213
|
+
*
|
|
214
|
+
* The browser calls the service with the user's own session: a `401` or `403` is the user's, and
|
|
215
|
+
* reaches the caller as it is (a Moost server answers its own credentials' refusal `502`). The
|
|
216
|
+
* failures a write maps by itself (a version mismatch of the caller's token, a missing entity) are
|
|
217
|
+
* the client's business, not this function's.
|
|
218
|
+
*/
|
|
219
|
+
function toClientError(error, context = {}) {
|
|
220
|
+
if (error instanceof _atscript_db_client.ClientError || error instanceof _atscript_db_client.TransportError) return error;
|
|
221
|
+
if (error instanceof _atscript_typescript_utils.ValidatorError) return validationError(error);
|
|
222
|
+
const failure = (0, _atscript_odata.dbFailureOf)(error, context);
|
|
223
|
+
if (failure) {
|
|
224
|
+
const { status, message, code, entries } = failure;
|
|
225
|
+
return withCause(new _atscript_db_client.ClientError(status, body(status, message, code, entries)), error);
|
|
226
|
+
}
|
|
227
|
+
if ((0, _atscript_odata.isODataError)(error)) return fromODataError(error, context);
|
|
228
|
+
if ((0, _atscript_odata.isODataServiceError)(error)) return new _atscript_db_client.TransportError("GET", error.link ?? context.url ?? "", error.message, error);
|
|
229
|
+
if ((0, _atscript_odata.isODataPayloadError)(error)) return new _atscript_db_client.TransportError("GET", context.url ?? "", error.message, error);
|
|
230
|
+
return error;
|
|
231
|
+
}
|
|
232
|
+
//#endregion
|
|
233
|
+
//#region src/batch.ts
|
|
234
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
235
|
+
const SENT = "This batch has been sent: give further calls a new one";
|
|
236
|
+
/**
|
|
237
|
+
* A new batch of the registered service `service`.
|
|
238
|
+
*
|
|
239
|
+
* @param engine the service's engine, once it is connected
|
|
240
|
+
*/
|
|
241
|
+
function createClientBatch(service, engine) {
|
|
242
|
+
const state = {
|
|
243
|
+
service,
|
|
244
|
+
engine,
|
|
245
|
+
changesets: /* @__PURE__ */ new Map(),
|
|
246
|
+
holds: /* @__PURE__ */ new Set(),
|
|
247
|
+
calls: [],
|
|
248
|
+
sending: false,
|
|
249
|
+
sealed: false
|
|
250
|
+
};
|
|
251
|
+
async function dispatch() {
|
|
252
|
+
while (state.holds.size > 0) await Promise.all(state.holds);
|
|
253
|
+
state.sealed = true;
|
|
254
|
+
if (state.batch) await state.batch.send(state.init?.send);
|
|
255
|
+
return Promise.allSettled(state.calls);
|
|
256
|
+
}
|
|
257
|
+
const batch = {
|
|
258
|
+
changeset() {
|
|
259
|
+
if (state.sealed) throw new Error(SENT);
|
|
260
|
+
const changeset = { batch };
|
|
261
|
+
states.set(changeset, {
|
|
262
|
+
state,
|
|
263
|
+
changeset
|
|
264
|
+
});
|
|
265
|
+
return changeset;
|
|
266
|
+
},
|
|
267
|
+
send() {
|
|
268
|
+
if (state.sending) throw new Error("This batch has been sent already");
|
|
269
|
+
state.sending = true;
|
|
270
|
+
return dispatch();
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
states.set(batch, { state });
|
|
274
|
+
return batch;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* The ticket of a client call given `option` as its `batch`; `undefined` for none or `false`.
|
|
278
|
+
*
|
|
279
|
+
* @throws TypeError for a value that is no batch or changeset of `createBatch()`; Error for a
|
|
280
|
+
* batch that has gone out.
|
|
281
|
+
*/
|
|
282
|
+
function joinBatch(option) {
|
|
283
|
+
if (option === void 0 || option === false) return void 0;
|
|
284
|
+
const found = typeof option === "object" && option !== null ? states.get(option) : void 0;
|
|
285
|
+
if (!found) throw new TypeError("The `batch` option takes false, or a batch or changeset of odata.createBatch()");
|
|
286
|
+
const { state, changeset } = found;
|
|
287
|
+
if (state.sealed) throw new Error(SENT);
|
|
288
|
+
let release;
|
|
289
|
+
const held = new Promise((resolve) => {
|
|
290
|
+
release = resolve;
|
|
291
|
+
});
|
|
292
|
+
state.holds.add(held);
|
|
293
|
+
let taken = false;
|
|
294
|
+
const ticket = {
|
|
295
|
+
release() {
|
|
296
|
+
state.holds.delete(held);
|
|
297
|
+
release();
|
|
298
|
+
},
|
|
299
|
+
track(promise) {
|
|
300
|
+
promise.catch(() => void 0);
|
|
301
|
+
state.calls.push(promise);
|
|
302
|
+
},
|
|
303
|
+
take(service) {
|
|
304
|
+
if (taken) return void 0;
|
|
305
|
+
taken = true;
|
|
306
|
+
if (service !== state.engine()) throw new TypeError(`A batch of service "${state.service}" carries calls of its own entity sets only: this client reads another service root (a value-help service, or another registered service)`);
|
|
307
|
+
return queueing(state, changeset, () => ticket.release());
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
return ticket;
|
|
311
|
+
}
|
|
312
|
+
/** The methods that queue a call's request in the batch, or in its changeset. */
|
|
313
|
+
function queueing(state, changeset, queued) {
|
|
314
|
+
/** The call's options without what belongs to the `$batch` request, once that is checked. */
|
|
315
|
+
function own(init) {
|
|
316
|
+
const { session, headers, batch: _batch, ...rest } = init ?? {};
|
|
317
|
+
const key = (0, _atscript_odata.headersKey)(headers);
|
|
318
|
+
if (!state.init) {
|
|
319
|
+
const send = {};
|
|
320
|
+
if (session) send.session = session;
|
|
321
|
+
if (headers) send.headers = headers;
|
|
322
|
+
state.init = {
|
|
323
|
+
send,
|
|
324
|
+
key
|
|
325
|
+
};
|
|
326
|
+
} else if (state.init.send.session !== session || state.init.key !== key) throw new TypeError("The calls of one batch go out as one HTTP request, with one session and one set of headers: this call's differ from the first one's (another session, locale or call headers)");
|
|
327
|
+
return rest;
|
|
328
|
+
}
|
|
329
|
+
/** The engine's batch, or the engine's changeset of `changeset`, for a write. */
|
|
330
|
+
function target(write) {
|
|
331
|
+
state.batch ??= state.engine().batch();
|
|
332
|
+
if (!changeset) return state.batch;
|
|
333
|
+
if (!write) throw new TypeError("A changeset holds writes only: give a read the batch itself");
|
|
334
|
+
let opened = state.changesets.get(changeset);
|
|
335
|
+
if (!opened) {
|
|
336
|
+
opened = state.batch.changeset();
|
|
337
|
+
state.changesets.set(changeset, opened);
|
|
338
|
+
}
|
|
339
|
+
return opened;
|
|
340
|
+
}
|
|
341
|
+
/** Queues the request (the engine plans a call synchronously), then lets the batch go. */
|
|
342
|
+
function run(queue) {
|
|
343
|
+
try {
|
|
344
|
+
return queue();
|
|
345
|
+
} finally {
|
|
346
|
+
queued();
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const read = () => target(false);
|
|
350
|
+
return {
|
|
351
|
+
read: (spec, init) => run(() => read().read(spec, own(init))),
|
|
352
|
+
readOne: (spec, init) => run(() => read().readOne(spec, own(init))),
|
|
353
|
+
count: (spec, init) => run(() => read().count(spec, own(init))),
|
|
354
|
+
aggregate: (spec, init) => run(() => read().aggregate(spec, own(init))),
|
|
355
|
+
create: (entitySet, data, init) => run(() => target(true).create(entitySet, data, own(init))),
|
|
356
|
+
update: (entitySet, key, patch, init) => run(() => target(true).update(entitySet, key, patch, own(init))),
|
|
357
|
+
replace: (entitySet, key, data, init) => run(() => target(true).replace(entitySet, key, data, own(init))),
|
|
358
|
+
remove: (entitySet, key, init) => run(() => target(true).remove(entitySet, key, own(init)))
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
//#endregion
|
|
362
|
+
//#region src/writes.ts
|
|
363
|
+
const WRITE_OPERATIONS = [
|
|
364
|
+
"insert",
|
|
365
|
+
"update",
|
|
366
|
+
"replace",
|
|
367
|
+
"remove"
|
|
368
|
+
];
|
|
369
|
+
/** The kind of write each operation is, as `writeRefusal` of `@atscript/odata` names it. */
|
|
370
|
+
const WRITES = {
|
|
371
|
+
insert: "insert",
|
|
372
|
+
update: "update",
|
|
373
|
+
replace: "update",
|
|
374
|
+
remove: "delete"
|
|
375
|
+
};
|
|
376
|
+
function own(record, key) {
|
|
377
|
+
return record && Object.hasOwn(record, key) ? record[key] : void 0;
|
|
378
|
+
}
|
|
379
|
+
/** A plain object, as a JSON payload holds one: not an array, a date or another class. */
|
|
380
|
+
function isPlainObject(value) {
|
|
381
|
+
if (typeof value !== "object" || value === null) return false;
|
|
382
|
+
const prototype = Object.getPrototypeOf(value);
|
|
383
|
+
return prototype === Object.prototype || prototype === null;
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Why the client may not run `operation` on the entity set `set` describes: what `writeRefusal`
|
|
387
|
+
* of `@atscript/odata` says, the rule a Moost server and the engine follow too; for a set the
|
|
388
|
+
* service model does not have (`set` undefined), `UNKNOWN_ENTITY_SET`. `undefined` when the
|
|
389
|
+
* write is allowed.
|
|
390
|
+
*/
|
|
391
|
+
function refusalOf(set, entitySet, operation) {
|
|
392
|
+
if (!set) return new _atscript_odata.ODataWriteError("UNKNOWN_ENTITY_SET", `"${operation}" is not possible: the service has no entity set "${entitySet}"`, { path: entitySet });
|
|
393
|
+
return (0, _atscript_odata.writeRefusal)(set, WRITES[operation]);
|
|
394
|
+
}
|
|
395
|
+
/** The writes the service allows on the entity set (`allowedWrites`), as moost-db lists them in `crud`. */
|
|
396
|
+
function writeCrud(set) {
|
|
397
|
+
const allowed = (0, _atscript_odata.allowedWrites)(set);
|
|
398
|
+
const crud = {};
|
|
399
|
+
for (const operation of WRITE_OPERATIONS) if (allowed[WRITES[operation]]) crud[operation] = [];
|
|
400
|
+
return crud;
|
|
401
|
+
}
|
|
402
|
+
/** The members of the entity type of an entity set. */
|
|
403
|
+
function membersOf(model, entitySet) {
|
|
404
|
+
const set = own(model.entitySets, entitySet);
|
|
405
|
+
return set ? (0, _atscript_odata.structuredMembers)(set.entityType, "entity", model) : void 0;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* The key of one entity, taken from a row or from an identifier object: every key property,
|
|
409
|
+
* nothing else.
|
|
410
|
+
*
|
|
411
|
+
* @param at prefix of the error path: `""`, or `[i].` for a row of an array
|
|
412
|
+
* @throws ODataQueryError `INVALID_KEY` naming the first key property that has no value.
|
|
413
|
+
*/
|
|
414
|
+
function keyOf(row, key, entitySet, at = "") {
|
|
415
|
+
if (key.length === 0) throw new _atscript_odata.ODataQueryError("INVALID_KEY", `${entitySet} declares no key`, { path: at });
|
|
416
|
+
const picked = {};
|
|
417
|
+
for (const name of key) {
|
|
418
|
+
const value = Object.hasOwn(row, name) ? row[name] : void 0;
|
|
419
|
+
if (value === void 0 || value === null) throw new _atscript_odata.ODataQueryError("INVALID_KEY", `${entitySet} is identified by ${key.join(", ")}: "${name}" has no value`, { path: `${at}${name}` });
|
|
420
|
+
picked[name] = value;
|
|
421
|
+
}
|
|
422
|
+
return picked;
|
|
423
|
+
}
|
|
424
|
+
/** `row` without its key properties: the members a partial update sends. */
|
|
425
|
+
function withoutKey(row, key) {
|
|
426
|
+
const rest = {};
|
|
427
|
+
for (const [name, value] of Object.entries(row)) if (!key.includes(name)) rest[name] = value;
|
|
428
|
+
return rest;
|
|
429
|
+
}
|
|
430
|
+
/** `$replace`, `$insert`, … : the array operators of an atscript-db patch. */
|
|
431
|
+
const ARRAY_OPERATORS = new Set([
|
|
432
|
+
"$replace",
|
|
433
|
+
"$insert",
|
|
434
|
+
"$upsert",
|
|
435
|
+
"$update",
|
|
436
|
+
"$remove"
|
|
437
|
+
]);
|
|
438
|
+
/** `$inc`, `$dec`, `$mul`: the field operators of an atscript-db patch. */
|
|
439
|
+
const FIELD_OPERATORS = new Set([
|
|
440
|
+
"$inc",
|
|
441
|
+
"$dec",
|
|
442
|
+
"$mul"
|
|
443
|
+
]);
|
|
444
|
+
/**
|
|
445
|
+
* One value of an atscript-db patch as an OData partial update sends it. A collection is always
|
|
446
|
+
* sent whole, so `{ $replace: [...] }` becomes the array itself; the other array operators and
|
|
447
|
+
* the field operators have no OData form and are refused. A nested object (a complex value under
|
|
448
|
+
* the merge strategy) is looked into, an array is sent as it is.
|
|
449
|
+
*/
|
|
450
|
+
function patchValue(value, path) {
|
|
451
|
+
if (!isPlainObject(value)) return value;
|
|
452
|
+
const keys = Object.keys(value);
|
|
453
|
+
const arrayOperators = keys.filter((name) => ARRAY_OPERATORS.has(name));
|
|
454
|
+
if (arrayOperators.length > 0) {
|
|
455
|
+
if (keys.length === 1 && keys[0] === "$replace") return value.$replace;
|
|
456
|
+
throw writeRefused("UNSUPPORTED_ARRAY_OPERATOR", path, `"${path}": ${arrayOperators.filter((name) => name !== "$replace").join(", ") || keys.join(", ")} cannot be sent to OData, which replaces a collection as a whole; send the whole array`);
|
|
457
|
+
}
|
|
458
|
+
const fieldOperators = keys.filter((name) => FIELD_OPERATORS.has(name));
|
|
459
|
+
if (fieldOperators.length > 0) throw writeRefused("UNSUPPORTED_FIELD_OPERATOR", path, `"${path}": ${fieldOperators.join(", ")} cannot be sent to OData, which has no arithmetic in an update; send the new value`);
|
|
460
|
+
let copy;
|
|
461
|
+
for (const name of keys) {
|
|
462
|
+
const next = patchValue(value[name], `${path}.${name}`);
|
|
463
|
+
if (next !== value[name]) (copy ??= { ...value })[name] = next;
|
|
464
|
+
}
|
|
465
|
+
return copy ?? value;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Checks one row of an update or replace (its `$cas` taken out by {@link versionOf}) for what
|
|
469
|
+
* OData cannot express and returns it in the form the engine sends:
|
|
470
|
+
*
|
|
471
|
+
* - a navigation member is refused (`UNSUPPORTED_DEEP_UPDATE`): an update or replace cannot
|
|
472
|
+
* change related entities;
|
|
473
|
+
* - an update (`patch`) has its operators translated: `$replace` becomes the array, every other
|
|
474
|
+
* array operator (`UNSUPPORTED_ARRAY_OPERATOR`) and field operator
|
|
475
|
+
* (`UNSUPPORTED_FIELD_OPERATOR`) is refused.
|
|
476
|
+
*
|
|
477
|
+
* Anything that is not a plain object comes back as it is, for the preflight to refuse.
|
|
478
|
+
*
|
|
479
|
+
* @param at prefix of the error path: `""`, or `[i].` for a row of an array
|
|
480
|
+
* @throws ClientError 400, or ODataWriteError `UNSUPPORTED_DEEP_UPDATE`, before anything is sent.
|
|
481
|
+
*/
|
|
482
|
+
function writableRow(row, members, patch, at) {
|
|
483
|
+
if (!isPlainObject(row)) return row;
|
|
484
|
+
let copy;
|
|
485
|
+
for (const [name, value] of Object.entries(row)) {
|
|
486
|
+
if (value === void 0) continue;
|
|
487
|
+
const path = `${at}${name}`;
|
|
488
|
+
if (own(members?.navigations, name)) throw new _atscript_odata.ODataWriteError("UNSUPPORTED_DEEP_UPDATE", `"${path}" is a navigation: an OData ${patch ? "update" : "replace"} cannot change related entities; write them one by one`, { path });
|
|
489
|
+
if (!patch) continue;
|
|
490
|
+
const next = patchValue(value, path);
|
|
491
|
+
if (next !== value) (copy ??= { ...row })[name] = next;
|
|
492
|
+
}
|
|
493
|
+
return copy ?? row;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Refuses `$cas` (`CAS_NOT_SUPPORTED`) where there is no version token to compare: on an insert,
|
|
497
|
+
* and on an entity set that declares no optimistic concurrency (its type has no
|
|
498
|
+
* `@db.column.version.token` field).
|
|
499
|
+
*/
|
|
500
|
+
function checkCas(row, at, why = "the entity set has no version token") {
|
|
501
|
+
if (!isPlainObject(row) || row.$cas === void 0) return;
|
|
502
|
+
const path = `${at}$cas`;
|
|
503
|
+
throw writeRefused("CAS_NOT_SUPPORTED", path, `"${path}": ${why}, so the write cannot be made conditional on one; leave $cas out (the write then overwrites the entity)`);
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* The version token a row of an update or replace carries, as moost-db reads it: `$cas` with
|
|
507
|
+
* the token field (`{ __etag: "<ETag>" }`), or the token field itself, a non-empty string, as a
|
|
508
|
+
* row comes from a read. Both are taken out of the row: the token is never sent as a property.
|
|
509
|
+
*
|
|
510
|
+
* @param token the type's `@db.column.version.token` field; without one, `$cas` is refused
|
|
511
|
+
* @throws ClientError 400 `CAS_NOT_SUPPORTED`: `$cas` without a token field, of another field or
|
|
512
|
+
* not a string, or different from the token field the row carries.
|
|
513
|
+
*/
|
|
514
|
+
function versionOf(row, token, at) {
|
|
515
|
+
if (!token) {
|
|
516
|
+
checkCas(row, at);
|
|
517
|
+
return { row };
|
|
518
|
+
}
|
|
519
|
+
if (!isPlainObject(row) || row.$cas === void 0 && !Object.hasOwn(row, token)) return { row };
|
|
520
|
+
const { $cas, [token]: carried, ...rest } = row;
|
|
521
|
+
let version = typeof carried === "string" && carried !== "" ? carried : void 0;
|
|
522
|
+
if ($cas !== void 0) {
|
|
523
|
+
const path = `${at}$cas`;
|
|
524
|
+
const entries = isPlainObject($cas) ? Object.entries($cas) : [];
|
|
525
|
+
const [name, value] = entries[0] ?? [];
|
|
526
|
+
if (entries.length !== 1 || name !== token || typeof value !== "string") throw writeRefused("CAS_NOT_SUPPORTED", path, `"${path}": an OData write is conditional on the entity's ETag, its version token: $cas: { ${token}: "<ETag>" }`);
|
|
527
|
+
if (version !== void 0 && version !== value) throw writeRefused("CAS_NOT_SUPPORTED", path, `"${path}": the version differs from the "${at}${token}" the row carries`);
|
|
528
|
+
version = value;
|
|
529
|
+
}
|
|
530
|
+
return version === void 0 ? { row: rest } : {
|
|
531
|
+
row: rest,
|
|
532
|
+
version
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
/** The version token field of an entity set's type: its `@db.column.version.token` property. */
|
|
536
|
+
function versionTokenOf(type) {
|
|
537
|
+
if (type.type.kind !== "object") return void 0;
|
|
538
|
+
for (const [name, prop] of type.type.props) if (prop.metadata.has("db.column.version.token")) return name;
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* What `Client` reports as the id of an inserted row: the key value for a single key property,
|
|
542
|
+
* the key object for a composite key, as moost-db answers. `undefined` without a key.
|
|
543
|
+
*/
|
|
544
|
+
function insertedIdOf(key, names) {
|
|
545
|
+
if (!key) return void 0;
|
|
546
|
+
return names.length === 1 ? key[names[0]] : key;
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* The key a created entity has when the service does not tell it: the key of the payload, when
|
|
550
|
+
* every key property is in it and none of them is filled in by the service (`computed`).
|
|
551
|
+
*/
|
|
552
|
+
function payloadKey(row, members) {
|
|
553
|
+
if (!members || members.key.length === 0) return void 0;
|
|
554
|
+
const key = {};
|
|
555
|
+
for (const name of members.key) {
|
|
556
|
+
const value = row[name];
|
|
557
|
+
if (value === void 0 || value === null || own(members.properties, name)?.computed) return;
|
|
558
|
+
key[name] = value;
|
|
559
|
+
}
|
|
560
|
+
return key;
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* The answer of an array insert of several rows, sent each in a changeset of its own, as a Moost
|
|
564
|
+
* server answers `insertMany`: `{ insertedCount, insertedIds }` when every row was created; when
|
|
565
|
+
* rows failed, {@link rowsFailed}: the first failed row's `ClientError` with every failed row's
|
|
566
|
+
* entries at that row and an `INSERTED` entry for each row created.
|
|
567
|
+
*
|
|
568
|
+
* @param mapped what a failed row's error is answered with (the client's `toClientError`)
|
|
569
|
+
*/
|
|
570
|
+
function insertedRows(settled, rows, idOf, mapped) {
|
|
571
|
+
const created = [];
|
|
572
|
+
const failed = [];
|
|
573
|
+
settled.forEach((outcome, index) => {
|
|
574
|
+
if (outcome.status === "rejected") failed.push({
|
|
575
|
+
index,
|
|
576
|
+
error: mapped(outcome.reason)
|
|
577
|
+
});
|
|
578
|
+
else created.push({
|
|
579
|
+
index,
|
|
580
|
+
insertedId: idOf(rows[index], outcome.value)
|
|
581
|
+
});
|
|
582
|
+
});
|
|
583
|
+
if (failed.length > 0) throw rowsFailed(rows.length, failed, created);
|
|
584
|
+
return {
|
|
585
|
+
insertedCount: created.length,
|
|
586
|
+
insertedIds: created.map((row) => row.insertedId)
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
//#endregion
|
|
590
|
+
//#region src/meta.ts
|
|
591
|
+
/** What a filterable field is taken to accept when the metadata lists no operators for it. */
|
|
592
|
+
const COMPARISONS = [
|
|
593
|
+
"$eq",
|
|
594
|
+
"$ne",
|
|
595
|
+
"$gt",
|
|
596
|
+
"$gte",
|
|
597
|
+
"$lt",
|
|
598
|
+
"$lte",
|
|
599
|
+
"$in",
|
|
600
|
+
"$nin",
|
|
601
|
+
"$exists"
|
|
602
|
+
];
|
|
603
|
+
const TEXT_COMPARISONS = [...COMPARISONS, "$regex"];
|
|
604
|
+
/** The relation annotations atscript-db reads a navigation by, each with its `direction`. */
|
|
605
|
+
const RELATION_KINDS = [
|
|
606
|
+
["db.rel.to", "to"],
|
|
607
|
+
["db.rel.from", "from"],
|
|
608
|
+
["db.rel.via", "via"],
|
|
609
|
+
["db.rel.store", "store"]
|
|
610
|
+
];
|
|
611
|
+
/** The `direction` of a navigation, `undefined` for any other property. */
|
|
612
|
+
function relationKind(node) {
|
|
613
|
+
const metadata = node.metadata;
|
|
614
|
+
return RELATION_KINDS.find(([key]) => metadata.has(key))?.[1];
|
|
615
|
+
}
|
|
616
|
+
/** Whether atscript-ui reads the node as text, the kind of value it offers pattern filters for. */
|
|
617
|
+
function isText(node) {
|
|
618
|
+
const def = node.type;
|
|
619
|
+
if (def.kind === "") return def.designType === "string";
|
|
620
|
+
return def.kind === "union" && (def.items ?? []).every((item) => isText(item));
|
|
621
|
+
}
|
|
622
|
+
function fieldMeta(node, field) {
|
|
623
|
+
const meta = {
|
|
624
|
+
sortable: field.sortable,
|
|
625
|
+
filterable: field.filterable
|
|
626
|
+
};
|
|
627
|
+
if (field.groupable && field.filterable) meta.groupable = true;
|
|
628
|
+
if (!field.filterable) return meta;
|
|
629
|
+
const allowed = field.allowedFilterOps;
|
|
630
|
+
if ((isText(node) ? TEXT_COMPARISONS : COMPARISONS).some((operator) => !allowed.includes(operator))) meta.filterOps = [...allowed];
|
|
631
|
+
return meta;
|
|
632
|
+
}
|
|
633
|
+
function collectFields(type, prefix, context) {
|
|
634
|
+
for (const [name, node] of type.props) {
|
|
635
|
+
if (relationKind(node)) continue;
|
|
636
|
+
const path = `${prefix}${name}`;
|
|
637
|
+
if (node.type.kind === "object") {
|
|
638
|
+
collectFields(node.type, `${path}.`, context);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
const meta = fieldMeta(node, context.describe(path));
|
|
642
|
+
if (prefix === "" && context.key.includes(name)) meta.indexed = true;
|
|
643
|
+
context.fields[path] = meta;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
function relationsOf(type, set) {
|
|
647
|
+
const relations = [];
|
|
648
|
+
for (const [name, node] of type.props) {
|
|
649
|
+
const direction = relationKind(node);
|
|
650
|
+
if (!direction) continue;
|
|
651
|
+
const navigation = set.navigations.find((candidate) => candidate.name === name);
|
|
652
|
+
if (!navigation?.expandable) continue;
|
|
653
|
+
const relation = {
|
|
654
|
+
name,
|
|
655
|
+
direction,
|
|
656
|
+
isArray: node.type.kind === "array"
|
|
657
|
+
};
|
|
658
|
+
if (navigation.filterable) relation.filterable = true;
|
|
659
|
+
relations.push(relation);
|
|
660
|
+
}
|
|
661
|
+
return relations;
|
|
662
|
+
}
|
|
663
|
+
function listed(...controls) {
|
|
664
|
+
return controls.filter((control) => control !== false);
|
|
665
|
+
}
|
|
666
|
+
/** The reads that work on the entity set, each with the controls it takes. */
|
|
667
|
+
function readCrudOf(set, relations) {
|
|
668
|
+
if (!set.addressable) return {};
|
|
669
|
+
const filter = set.filterable && "filter";
|
|
670
|
+
const expand = relations.length > 0 && "with";
|
|
671
|
+
const shared = listed(set.sortable && "sort", "select", set.searchable && "search", expand);
|
|
672
|
+
const groupBy = set.aggregateFns.length > 0 && "groupBy";
|
|
673
|
+
const crud = {
|
|
674
|
+
query: listed(filter, "skip", "limit", set.countable && "count", ...shared, groupBy),
|
|
675
|
+
one: listed("select", expand)
|
|
676
|
+
};
|
|
677
|
+
if (set.countable) crud.pages = listed(filter, "page", "size", ...shared);
|
|
678
|
+
return crud;
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Builds the `/meta` response of an OData entity set: what `@atscript/moost-db` answers on
|
|
682
|
+
* `GET /meta` for a table, computed from the service model and the entity set's annotated type.
|
|
683
|
+
*
|
|
684
|
+
* - `type`: serialized by `serializeMetaType` of `@atscript/db/meta`, the code moost-db serves
|
|
685
|
+
* `/meta` with, so the two are byte-identical for the same type. A property the service
|
|
686
|
+
* computes (`Core.Computed`, v2 `sap:creatable` and `sap:updatable` false, a store-generated
|
|
687
|
+
* column) carries `@meta.readonly` and, when it is a scalar, `@db.default.store` from the
|
|
688
|
+
* generator: forms show it read-only, and they and the insert preflight let an insert leave it
|
|
689
|
+
* out although the type requires it (a key the service assigns).
|
|
690
|
+
* - `fields`: one entry per scalar or collection leaf of the type, nested objects flattened with
|
|
691
|
+
* `.`; navigations and nested-object parents are not listed. `sortable` / `filterable` are the
|
|
692
|
+
* entity set's capabilities. `filterOps` is present where a filterable field accepts less than
|
|
693
|
+
* every comparison (and patterns, for text): a filter restriction of the service, or text that
|
|
694
|
+
* is no `Edm.String` and therefore takes no `$regex`.
|
|
695
|
+
* - `primaryKeys` / `preferredId`: the entity key.
|
|
696
|
+
* - `relations`: the navigations the type carries and the service expands, each with the
|
|
697
|
+
* `direction` of its annotation: `to` / `from` over a foreign key, `store` for one without
|
|
698
|
+
* (`@db.rel.store`, which the generator emits where the service declares no usable foreign
|
|
699
|
+
* key). All of them are read through `$expand`.
|
|
700
|
+
* - `versionColumn`: the version token field (`@db.column.version.token`, the entity's ETag) of an
|
|
701
|
+
* entity set with optimistic concurrency; absent without one. atscript-ui keeps it out of the
|
|
702
|
+
* columns and forms, db-client's validator lifts it into `$cas`.
|
|
703
|
+
* - `crud`: the reads that work, with their controls, and the writes the service allows:
|
|
704
|
+
* `insert` (insertable), `update` and `replace` (updatable), `remove` (deletable), each `[]`.
|
|
705
|
+
* A set that is not addressable or is draft-enabled lists no write.
|
|
706
|
+
* - aggregation: `aggregateFns` lists the functions of the set's `$apply` (none without it),
|
|
707
|
+
* `groupable` marks the filterable single values of such a set, and `crud.query` takes
|
|
708
|
+
* `groupBy`; expressions, conditions, field lists and two-level aggregates are off.
|
|
709
|
+
* - search, vector and geo: `searchable` follows the entity set, the rest is off.
|
|
710
|
+
* - `actions`: the ones given (`options.actions`), else none.
|
|
711
|
+
*
|
|
712
|
+
* @throws Error when the model has no such entity set or the type is not an interface.
|
|
713
|
+
*/
|
|
714
|
+
function buildMeta(options) {
|
|
715
|
+
const { model, entitySet, type } = options;
|
|
716
|
+
if (!Object.hasOwn(model.entitySets, entitySet)) throw new Error(`The service model has no entity set "${entitySet}"`);
|
|
717
|
+
if (type.type.kind !== "object") throw new Error(`The type of entity set "${entitySet}" is not an interface`);
|
|
718
|
+
const object = type.type;
|
|
719
|
+
const context = options.context ?? {
|
|
720
|
+
version: model.version,
|
|
721
|
+
dialect: (0, _atscript_odata.dialectFor)(model)
|
|
722
|
+
};
|
|
723
|
+
const set = (0, _atscript_odata.describeEntitySet)(model, entitySet, context);
|
|
724
|
+
const fields = {};
|
|
725
|
+
const describe = (path) => (0, _atscript_odata.describeField)(model, entitySet, path, context);
|
|
726
|
+
collectFields(object, "", {
|
|
727
|
+
describe,
|
|
728
|
+
key: set.key,
|
|
729
|
+
fields
|
|
730
|
+
});
|
|
731
|
+
const relations = relationsOf(object, set);
|
|
732
|
+
const primaryKeys = set.key.filter((name) => object.props.has(name));
|
|
733
|
+
const versionColumn = [...object.props].find(([, prop]) => prop.metadata.has("db.column.version"))?.[0];
|
|
734
|
+
return {
|
|
735
|
+
searchable: set.addressable && set.searchable,
|
|
736
|
+
vectorSearchable: false,
|
|
737
|
+
geoSearchable: false,
|
|
738
|
+
searchIndexes: [],
|
|
739
|
+
primaryKeys,
|
|
740
|
+
preferredId: [...primaryKeys],
|
|
741
|
+
relations,
|
|
742
|
+
fields,
|
|
743
|
+
type: (0, _atscript_db_meta.serializeMetaType)(type),
|
|
744
|
+
actions: [...options.actions ?? []],
|
|
745
|
+
crud: {
|
|
746
|
+
...readCrudOf(set, relations),
|
|
747
|
+
...writeCrud(set)
|
|
748
|
+
},
|
|
749
|
+
...versionColumn === void 0 ? {} : { versionColumn },
|
|
750
|
+
aggregateFns: [...set.aggregateFns],
|
|
751
|
+
aggregateExpressions: false,
|
|
752
|
+
conditionalAggregates: false,
|
|
753
|
+
distinctFieldLists: false,
|
|
754
|
+
nestedAggregates: false
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
//#endregion
|
|
758
|
+
//#region src/operations.ts
|
|
759
|
+
/**
|
|
760
|
+
* The db actions of an entity set, as a Moost server's generated base declares them: every
|
|
761
|
+
* operation of the connection's selection bound to the set's type, named by its key in `ops` (the
|
|
762
|
+
* local name), at its level, with `processor: "backend"`, the label of the live type
|
|
763
|
+
* (`@meta.label`, else the local name) and `inputForm` when the type has properties. An operation
|
|
764
|
+
* whose type the connection lacks cannot be called and is left out.
|
|
765
|
+
*
|
|
766
|
+
* @param url the URL the client is known by: `value` is `<url>/actions/<name>`, the route a Moost
|
|
767
|
+
* server serves the action at (nothing is fetched from it)
|
|
768
|
+
*/
|
|
769
|
+
function setActions(connection, entitySet, url) {
|
|
770
|
+
const group = (0, _atscript_odata.opsLayout)({ operations: (0, _atscript_odata.operationsOf)(connection) }).sets.find((set) => set.entitySet === entitySet);
|
|
771
|
+
const actions = [];
|
|
772
|
+
for (const { key, op } of group?.entries ?? []) {
|
|
773
|
+
const form = connection.types[op.type];
|
|
774
|
+
if (!form) continue;
|
|
775
|
+
const label = form.metadata.get("meta.label");
|
|
776
|
+
const info = {
|
|
777
|
+
name: key,
|
|
778
|
+
label: typeof label === "string" && label !== "" ? label : op.localName,
|
|
779
|
+
level: op.level ?? "table",
|
|
780
|
+
processor: "backend",
|
|
781
|
+
value: `${url}/actions/${key}`
|
|
782
|
+
};
|
|
783
|
+
if (form.type.props?.size) info.inputForm = op.type;
|
|
784
|
+
const writes = (0, _atscript_odata.operationWrites)((0, _atscript_odata.operationOf)(connection.service.model, op));
|
|
785
|
+
actions.push({
|
|
786
|
+
info,
|
|
787
|
+
op,
|
|
788
|
+
form,
|
|
789
|
+
writes
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
return actions;
|
|
793
|
+
}
|
|
794
|
+
/** The value at a dot path of a row. */
|
|
795
|
+
function valueAt(row, path) {
|
|
796
|
+
let value = row;
|
|
797
|
+
for (const segment of path.split(".")) {
|
|
798
|
+
if (value === null || typeof value !== "object") return void 0;
|
|
799
|
+
value = value[segment];
|
|
800
|
+
}
|
|
801
|
+
return value;
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* Whether the live service offers the action on the row: its availability path (`available`)
|
|
805
|
+
* is not `false` there. `null` or a missing value is unknown: the service decides.
|
|
806
|
+
*/
|
|
807
|
+
function offered(action, row) {
|
|
808
|
+
return action.op.available === void 0 || valueAt(row, action.op.available) !== false;
|
|
809
|
+
}
|
|
810
|
+
/** Deletes the value at a dot path of a row, and the objects on the way that it leaves empty. */
|
|
811
|
+
function dropPath(row, path) {
|
|
812
|
+
const segments = path.split(".");
|
|
813
|
+
const parents = [row];
|
|
814
|
+
for (const segment of segments.slice(0, -1)) {
|
|
815
|
+
const next = parents.at(-1)[segment];
|
|
816
|
+
if (next === null || typeof next !== "object") return;
|
|
817
|
+
parents.push(next);
|
|
818
|
+
}
|
|
819
|
+
delete parents.at(-1)[segments.at(-1)];
|
|
820
|
+
for (let i = parents.length - 1; i > 0; i--) {
|
|
821
|
+
if (Object.keys(parents[i]).length > 0) break;
|
|
822
|
+
delete parents[i - 1][segments[i - 1]];
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
/** The entity set a run is bound to: the input's, or that of the operation's handle. */
|
|
826
|
+
function runEntitySet(input) {
|
|
827
|
+
return typeof input.operation === "string" ? input.entitySet : input.operation.entitySet;
|
|
828
|
+
}
|
|
829
|
+
/** What moost-db answers a `412` on a row's token: the entity read, its current token, or `404`. */
|
|
830
|
+
async function staleRow(connection, entitySet, row, init) {
|
|
831
|
+
const { service } = connection;
|
|
832
|
+
const set = (0, _atscript_odata.describeEntitySet)(service.model, entitySet, service.context);
|
|
833
|
+
const key = Object.fromEntries(set.key.map((name) => [name, row[name]]));
|
|
834
|
+
const current = await service.readOne({
|
|
835
|
+
entitySet,
|
|
836
|
+
key
|
|
837
|
+
}, init);
|
|
838
|
+
return current ? versionMismatch(current.etag) : notFound();
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Runs an operation with the core runner (`runOperation` of `@atscript/odata`). A browser
|
|
842
|
+
* connection holds no verdicts: what the live service has is called, and what it lacks fails
|
|
843
|
+
* (`UNKNOWN_OPERATION`).
|
|
844
|
+
*
|
|
845
|
+
* A call that sends a row's version token (`__etag`: a call that writes; see `sendsRowToken`) which
|
|
846
|
+
* the service refuses with `412` is answered as moost-db answers a stale write: the entity is read,
|
|
847
|
+
* and the error is a `VersionMismatchError` with its current token, or a 404 when it is gone; on
|
|
848
|
+
* one row it is thrown, on several it is that row's error in `failed`. Without the token the runner
|
|
849
|
+
* reads the ETag itself (on one row again after a `412`, three attempts, then
|
|
850
|
+
* `SERIALIZATION_FAILURE`). A row the service has no entity for (that read finds none, or the call
|
|
851
|
+
* is answered `404` or `410`) is moost-db's 404 (`notFound()`), as a Moost server answers it.
|
|
852
|
+
* Anything else is left as the engine throws it.
|
|
853
|
+
*/
|
|
854
|
+
async function callOperation(connection, input, init) {
|
|
855
|
+
const rows = input.rows ?? [];
|
|
856
|
+
const entitySet = runEntitySet(input);
|
|
857
|
+
const sendsToken = (0, _atscript_odata.sendsRowToken)(connection, input);
|
|
858
|
+
/** A `412` on the row's own token: its version mismatch. */
|
|
859
|
+
const stale = (row, error) => sendsToken && entitySet !== void 0 && typeof row?.[_atscript_odata.VERSION_TOKEN] === "string" && row[_atscript_odata.VERSION_TOKEN] !== "" && (0, _atscript_odata.writeFailureOf)(error) === "changed";
|
|
860
|
+
/** The answer of a row's failure: its version mismatch, its 404, else the engine's error. */
|
|
861
|
+
const rowError = async (row, error) => {
|
|
862
|
+
if (stale(row, error)) return staleRow(connection, entitySet, row, init);
|
|
863
|
+
return (0, _atscript_odata.writeFailureOf)(error) === "not-found" ? notFound() : error;
|
|
864
|
+
};
|
|
865
|
+
let answer;
|
|
866
|
+
try {
|
|
867
|
+
answer = await (0, _atscript_odata.runOperation)(connection, input, init);
|
|
868
|
+
} catch (error) {
|
|
869
|
+
throw rows.length === 1 ? await rowError(rows[0], error) : error;
|
|
870
|
+
}
|
|
871
|
+
if (answer.failed) answer.failed = await Promise.all(answer.failed.map(async ({ index, error }) => ({
|
|
872
|
+
index,
|
|
873
|
+
error: await rowError(rows[index], error)
|
|
874
|
+
})));
|
|
875
|
+
return answer;
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* The answer of an action on rows, as a Moost server's generated base answers it: moost-db's action
|
|
879
|
+
* target summary (`matched`, `processed`, `skipped`, `failed` with each row's `status` and
|
|
880
|
+
* `code`), with one `value` per row and the service's messages. The browser has no availability
|
|
881
|
+
* gate: every given row is run, none skipped. Every row failed: {@link rowsFailed} (one row
|
|
882
|
+
* never comes here: the runner throws its error).
|
|
883
|
+
*
|
|
884
|
+
* @param mapped what a failed row's error is answered with (the client's `toClientError`)
|
|
885
|
+
*/
|
|
886
|
+
function rowsAnswer(answer, rows, key, mapped) {
|
|
887
|
+
const failed = (answer.failed ?? []).map(({ index, error }) => ({
|
|
888
|
+
index,
|
|
889
|
+
error: mapped(error)
|
|
890
|
+
}));
|
|
891
|
+
if (failed.length > 0 && failed.length === rows.length) throw rowsFailed(rows.length, failed);
|
|
892
|
+
const result = {
|
|
893
|
+
matched: rows.length,
|
|
894
|
+
processed: rows.length - failed.length,
|
|
895
|
+
skipped: [],
|
|
896
|
+
failed: failed.map(({ index, error }) => {
|
|
897
|
+
const id = Object.fromEntries(key.map((name) => [name, rows[index][name]]));
|
|
898
|
+
if (!(error instanceof _atscript_db_client.ClientError)) return {
|
|
899
|
+
id,
|
|
900
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
901
|
+
status: 500
|
|
902
|
+
};
|
|
903
|
+
const { code } = error.body;
|
|
904
|
+
return Object.assign({
|
|
905
|
+
id,
|
|
906
|
+
reason: error.body.message,
|
|
907
|
+
status: error.status
|
|
908
|
+
}, code ? { code } : {});
|
|
909
|
+
}),
|
|
910
|
+
value: answer.value
|
|
911
|
+
};
|
|
912
|
+
if (answer.message !== void 0) result.message = answer.message;
|
|
913
|
+
if (answer.messages) result.messages = answer.messages;
|
|
914
|
+
if (answer.details) result.details = answer.details;
|
|
915
|
+
return result;
|
|
916
|
+
}
|
|
917
|
+
//#endregion
|
|
918
|
+
//#region src/client.ts
|
|
919
|
+
/** Rows `query()` returns when the query sets no `$limit`, as moost-db's `/query` does. */
|
|
920
|
+
const DEFAULT_QUERY_LIMIT = 1e3;
|
|
921
|
+
/** Controls a table sends that mean nothing to a read here; they are accepted and ignored. */
|
|
922
|
+
const IGNORED_CONTROLS = ["$actions"];
|
|
923
|
+
/** Where a call given `{ batch }` keeps its ticket, on its own copy of the options. */
|
|
924
|
+
const TICKET = Symbol("batch ticket");
|
|
925
|
+
/**
|
|
926
|
+
* The session of the clients of a service whose call defaults name none: one per service, the
|
|
927
|
+
* one the service was created with (its transport's), else created on first use, held by the
|
|
928
|
+
* service object. In a browser the cookies are the browser's and the session keeps the CSRF
|
|
929
|
+
* token; without one, every write whose call carries its own headers (the locale) would fetch a
|
|
930
|
+
* token of its own.
|
|
931
|
+
*/
|
|
932
|
+
const sessions = /* @__PURE__ */ new WeakMap();
|
|
933
|
+
/** The session the clients of `service` share: the service's own, else one created on first use. */
|
|
934
|
+
function sharedSession(service) {
|
|
935
|
+
let session = sessions.get(service);
|
|
936
|
+
if (!session) {
|
|
937
|
+
session = service.transport.session ?? (0, _atscript_odata.createSession)();
|
|
938
|
+
sessions.set(service, session);
|
|
939
|
+
}
|
|
940
|
+
return session;
|
|
941
|
+
}
|
|
942
|
+
/** Makes `session` the one the clients of `service` share (that of the service referencing it). */
|
|
943
|
+
function shareSession(service, session) {
|
|
944
|
+
sessions.set(service, session);
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* The options of one OData call of the clients of `service` (and of the factory's `call`): the
|
|
948
|
+
* call defaults, the session the clients share unless the defaults name one, the call's signal
|
|
949
|
+
* and `batch: false`, and `locale` sent as `Accept-Language`, so the texts the service translates
|
|
950
|
+
* (text properties, messages) come in it; unless the defaults' headers name one (they win), or
|
|
951
|
+
* there is no locale.
|
|
952
|
+
*/
|
|
953
|
+
function callInit(defaults, service, opts, locale) {
|
|
954
|
+
const init = { ...defaults };
|
|
955
|
+
init.session ??= sharedSession(service);
|
|
956
|
+
if (opts?.signal) init.signal = opts.signal;
|
|
957
|
+
if (opts?.batch === false) init.batch = false;
|
|
958
|
+
return (0, _atscript_odata.withLocale)(init, locale);
|
|
959
|
+
}
|
|
960
|
+
/** Whether a select of `by` reads `path`: the path itself, or a property it lies in. */
|
|
961
|
+
const taken = (path, by) => path === by || path.startsWith(`${by}.`);
|
|
962
|
+
const names = (actions) => actions.map((action) => action.info.name);
|
|
963
|
+
/** The availability paths of actions, each once. */
|
|
964
|
+
const availabilityPaths = (actions) => [...new Set(actions.flatMap((action) => action.op.available ?? []))];
|
|
965
|
+
/** What a value is, as db-client's `action()` names a wrong identifier. */
|
|
966
|
+
function shapeOf(value) {
|
|
967
|
+
if (value === null) return "null";
|
|
968
|
+
if (Array.isArray(value)) return "array";
|
|
969
|
+
return typeof value;
|
|
970
|
+
}
|
|
971
|
+
function wholeNumber(value, fallback) {
|
|
972
|
+
const number = Math.trunc(Number(value));
|
|
973
|
+
return Number.isFinite(number) && number >= 1 ? number : fallback;
|
|
974
|
+
}
|
|
975
|
+
/**
|
|
976
|
+
* The implementation behind {@link ODataClient}: every public member of db-client's `Client`
|
|
977
|
+
* (`ClientLike`), without extending the class. Its own methods are typed loosely; the exported
|
|
978
|
+
* `ODataClient` type gives them the signatures of `Client<T, D, ODataClientCallOptions>`.
|
|
979
|
+
*/
|
|
980
|
+
var ODataEntityClient = class {
|
|
981
|
+
entitySet;
|
|
982
|
+
url;
|
|
983
|
+
target;
|
|
984
|
+
connect;
|
|
985
|
+
locale;
|
|
986
|
+
queryLimit;
|
|
987
|
+
callDefaults;
|
|
988
|
+
errorContext;
|
|
989
|
+
/**
|
|
990
|
+
* The version token field of the type (`@db.column.version.token`, which the generator emits on
|
|
991
|
+
* an entity set with optimistic concurrency); `undefined` when it has none.
|
|
992
|
+
*/
|
|
993
|
+
token;
|
|
994
|
+
described;
|
|
995
|
+
loadedMeta;
|
|
996
|
+
loadedEtag;
|
|
997
|
+
loadedValidator;
|
|
998
|
+
loadedActions;
|
|
999
|
+
constructor(options) {
|
|
1000
|
+
const { service, type } = options;
|
|
1001
|
+
if (!(service && type) && !options.connect) throw new Error("ODataClient: pass `service` and `type`, or `connect`");
|
|
1002
|
+
const declared = type ? type.metadata.get("db.http.path") : void 0;
|
|
1003
|
+
const url = options.url ?? (typeof declared === "string" ? declared : options.entitySet);
|
|
1004
|
+
this.entitySet = options.entitySet;
|
|
1005
|
+
this.url = url;
|
|
1006
|
+
this.locale = options.locale;
|
|
1007
|
+
this.queryLimit = options.queryLimit ?? 1e3;
|
|
1008
|
+
this.callDefaults = options.call ?? {};
|
|
1009
|
+
this.errorContext = {
|
|
1010
|
+
entitySet: options.entitySet,
|
|
1011
|
+
url
|
|
1012
|
+
};
|
|
1013
|
+
if (service && type) this.settle({
|
|
1014
|
+
service,
|
|
1015
|
+
type,
|
|
1016
|
+
operations: options.operations
|
|
1017
|
+
});
|
|
1018
|
+
else this.connect = options.connect;
|
|
1019
|
+
}
|
|
1020
|
+
/** The engine the client reads through. Known once the client is connected. */
|
|
1021
|
+
get service() {
|
|
1022
|
+
return this.connected().service;
|
|
1023
|
+
}
|
|
1024
|
+
/** The type of the entity set. Known once the client is connected. */
|
|
1025
|
+
get type() {
|
|
1026
|
+
return this.connected().type;
|
|
1027
|
+
}
|
|
1028
|
+
connected() {
|
|
1029
|
+
if (!this.target) throw new Error(`The client of "${this.url}" is not connected yet: call one of its methods first`);
|
|
1030
|
+
return this.target;
|
|
1031
|
+
}
|
|
1032
|
+
settle(target) {
|
|
1033
|
+
this.target = target;
|
|
1034
|
+
this.token = versionTokenOf(target.type);
|
|
1035
|
+
this.errorContext = {
|
|
1036
|
+
...this.errorContext,
|
|
1037
|
+
model: target.service.model
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
/** Resolves once the service and the type are known. */
|
|
1041
|
+
async ready() {
|
|
1042
|
+
if (!this.target) this.settle(await this.connect());
|
|
1043
|
+
}
|
|
1044
|
+
query(query, opts) {
|
|
1045
|
+
const uniquery = query;
|
|
1046
|
+
return this.guarded(opts, async (call) => {
|
|
1047
|
+
if ((uniquery?.controls)?.$count) return this.engine(call).count(this.countSpec(uniquery), this.init(call));
|
|
1048
|
+
const spec = this.stableOrder(this.spec(uniquery), false);
|
|
1049
|
+
if (spec.top === void 0 && this.queryLimit > 0) spec.top = this.queryLimit;
|
|
1050
|
+
return this.actionHints(spec, uniquery?.controls)(this.rowsOf(await this.engine(call).read(spec, this.init(call))));
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
count(query, opts) {
|
|
1054
|
+
return this.guarded(opts, (call) => this.engine(call).count(this.countSpec(query), this.init(call)));
|
|
1055
|
+
}
|
|
1056
|
+
pages(query, page = 1, size = 10, opts) {
|
|
1057
|
+
const uniquery = query;
|
|
1058
|
+
return this.guarded(opts, async (call) => {
|
|
1059
|
+
const $page = wholeNumber(page, 1);
|
|
1060
|
+
const $size = wholeNumber(size, 10);
|
|
1061
|
+
const controls = {
|
|
1062
|
+
...uniquery?.controls,
|
|
1063
|
+
$page,
|
|
1064
|
+
$size,
|
|
1065
|
+
$count: true
|
|
1066
|
+
};
|
|
1067
|
+
const spec = this.stableOrder(this.spec({
|
|
1068
|
+
...uniquery,
|
|
1069
|
+
controls
|
|
1070
|
+
}), true);
|
|
1071
|
+
const finish = this.actionHints(spec, controls);
|
|
1072
|
+
const result = await this.engine(call).read(spec, this.init(call));
|
|
1073
|
+
const count = result.count ?? 0;
|
|
1074
|
+
return {
|
|
1075
|
+
data: finish(this.rowsOf(result)),
|
|
1076
|
+
page: $page,
|
|
1077
|
+
itemsPerPage: $size,
|
|
1078
|
+
pages: Math.ceil(count / $size),
|
|
1079
|
+
count
|
|
1080
|
+
};
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* A grouped read, as one OData v4 `$apply` request (see `planAggregate` of `@atscript/odata`): the
|
|
1085
|
+
* rows of each group with the grouped fields and every aggregate under its alias; with
|
|
1086
|
+
* `$count`, `[{ count }]`, the number of groups, as moost-db answers it.
|
|
1087
|
+
*/
|
|
1088
|
+
aggregate(query, opts) {
|
|
1089
|
+
return this.guarded(opts, async (call) => {
|
|
1090
|
+
const spec = (0, _atscript_odata.aggregateSpecFromUniquery)(this.entitySet, query, { ignoreControls: IGNORED_CONTROLS });
|
|
1091
|
+
if (spec.count) {
|
|
1092
|
+
delete spec.skip;
|
|
1093
|
+
spec.top = 0;
|
|
1094
|
+
}
|
|
1095
|
+
const result = await this.engine(call).aggregate(spec, this.init(call));
|
|
1096
|
+
return spec.count ? [{ count: result.count }] : result.rows;
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
one(id, query, opts) {
|
|
1100
|
+
const controls = query?.controls;
|
|
1101
|
+
return this.guarded(opts, async (call) => {
|
|
1102
|
+
const spec = {
|
|
1103
|
+
...this.spec(controls && { controls }),
|
|
1104
|
+
key: this.key(id)
|
|
1105
|
+
};
|
|
1106
|
+
const finish = this.actionHints(spec, controls);
|
|
1107
|
+
const found = await this.engine(call).readOne(spec, this.init(call));
|
|
1108
|
+
return found ? finish([this.withToken(found.row, found.etag)])[0] : null;
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
insert(data, opts) {
|
|
1112
|
+
return this.guarded(opts, async (call) => {
|
|
1113
|
+
this.allow("insert");
|
|
1114
|
+
if (opts?.onConflict === "ignore") throw new _atscript_odata.ODataQueryError("UNSUPPORTED_CONTROL", "onConflict \"ignore\" is not supported: an OData service has no way to skip an entity that already exists", { path: "$onConflict" });
|
|
1115
|
+
const many = Array.isArray(data);
|
|
1116
|
+
if (many) this.single(call, "insert");
|
|
1117
|
+
(many ? data : [data]).forEach((item, index) => checkCas(item, many ? `[${index}].` : "", "a create is not compared with a version"));
|
|
1118
|
+
const rows = this.asRows(await this.preflight(data, "insert")).map((row) => this.withoutToken(row));
|
|
1119
|
+
const members = membersOf(this.service.model, this.entitySet);
|
|
1120
|
+
const key = this.describe().key;
|
|
1121
|
+
const idOf = (row, result) => insertedIdOf(result.key ?? payloadKey(row, members), key);
|
|
1122
|
+
if (!many || rows.length === 1) {
|
|
1123
|
+
const init = this.writeInit(call, opts?.returning && !many ? { returnEntity: true } : void 0);
|
|
1124
|
+
const created = await this.row(false, 0, () => this.engine(call).create(this.entitySet, rows[0], init));
|
|
1125
|
+
if (many) return {
|
|
1126
|
+
insertedCount: 1,
|
|
1127
|
+
insertedIds: [idOf(rows[0], created)]
|
|
1128
|
+
};
|
|
1129
|
+
const result = { insertedId: idOf(rows[0], created) };
|
|
1130
|
+
if (opts?.returning && created.row) result.row = this.withToken(created.row, created.etag);
|
|
1131
|
+
return result;
|
|
1132
|
+
}
|
|
1133
|
+
const { batch: off, ...init } = this.writeInit(call);
|
|
1134
|
+
return insertedRows(await (0, _atscript_odata.sendEach)(this.service, rows.length, (index, target) => target.batch ? target.batch.create(this.entitySet, rows[index]) : this.service.create(this.entitySet, rows[index], target.init), init, off === false ? { batch: false } : {}), rows, idOf, (error) => toClientError(error, this.errorContext));
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
update(data, opts) {
|
|
1138
|
+
return this.changeAll("update", data, opts);
|
|
1139
|
+
}
|
|
1140
|
+
replace(data, opts) {
|
|
1141
|
+
return this.changeAll("replace", data, opts);
|
|
1142
|
+
}
|
|
1143
|
+
remove(id, opts) {
|
|
1144
|
+
return this.guarded(opts, async (call) => {
|
|
1145
|
+
this.allow("remove");
|
|
1146
|
+
const key = keyOf(this.key(id), this.describe().key, this.entitySet);
|
|
1147
|
+
const { matched } = await (0, _atscript_odata.changeByKey)((etag) => this.engine(call).remove(this.entitySet, key, this.writeInit(call, void 0, etag)), this.byKey(key, call));
|
|
1148
|
+
if (!matched) throw notFound();
|
|
1149
|
+
return { deletedCount: 1 };
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
meta() {
|
|
1153
|
+
if (!this.loadedMeta) {
|
|
1154
|
+
const loading = this.ready().then(() => {
|
|
1155
|
+
const meta = buildMeta({
|
|
1156
|
+
model: this.service.model,
|
|
1157
|
+
entitySet: this.entitySet,
|
|
1158
|
+
type: this.type,
|
|
1159
|
+
context: this.service.context,
|
|
1160
|
+
actions: this.actions.map((action) => action.info)
|
|
1161
|
+
});
|
|
1162
|
+
this.loadedEtag = `W/"meta-${(0, _atscript_odata.metadataDigest)(JSON.stringify(meta))}"`;
|
|
1163
|
+
return meta;
|
|
1164
|
+
});
|
|
1165
|
+
loading.catch(() => {
|
|
1166
|
+
if (this.loadedMeta === loading) this.loadedMeta = void 0;
|
|
1167
|
+
});
|
|
1168
|
+
this.loadedMeta = loading;
|
|
1169
|
+
}
|
|
1170
|
+
return this.loadedMeta;
|
|
1171
|
+
}
|
|
1172
|
+
metaEtag() {
|
|
1173
|
+
return this.loadedEtag;
|
|
1174
|
+
}
|
|
1175
|
+
/** The metadata is built locally and never revalidated over HTTP: there is no store. */
|
|
1176
|
+
get metaStore() {}
|
|
1177
|
+
invalidateMeta() {
|
|
1178
|
+
this.loadedMeta = void 0;
|
|
1179
|
+
this.loadedEtag = void 0;
|
|
1180
|
+
this.loadedValidator = void 0;
|
|
1181
|
+
}
|
|
1182
|
+
getValidator() {
|
|
1183
|
+
if (!this.loadedValidator) {
|
|
1184
|
+
const loading = Promise.all([this.meta(), import("@atscript/db-client/validator")]).then(([meta, { createClientValidator }]) => createClientValidator(meta)).catch((error) => {
|
|
1185
|
+
if (this.loadedValidator === loading) this.loadedValidator = void 0;
|
|
1186
|
+
throw error;
|
|
1187
|
+
});
|
|
1188
|
+
this.loadedValidator = loading;
|
|
1189
|
+
}
|
|
1190
|
+
return this.loadedValidator;
|
|
1191
|
+
}
|
|
1192
|
+
/**
|
|
1193
|
+
* The row-level actions the live service offers on one row, by its availability (one read of
|
|
1194
|
+
* the key and the availability paths): `{ actions }`, as moost-db's `GET /meta/actions/:id`
|
|
1195
|
+
* answers; `{ actions: [] }` for a row that does not exist. A hint: no call is refused by it.
|
|
1196
|
+
*/
|
|
1197
|
+
async availableActions(id) {
|
|
1198
|
+
return this.guarded(void 0, async () => {
|
|
1199
|
+
const actions = this.rowActions();
|
|
1200
|
+
if (actions.length === 0) return { actions: [] };
|
|
1201
|
+
const $select = [...this.describe().key, ...availabilityPaths(actions)];
|
|
1202
|
+
const spec = {
|
|
1203
|
+
...this.spec({ controls: { $select } }),
|
|
1204
|
+
key: this.key(id)
|
|
1205
|
+
};
|
|
1206
|
+
const found = await this.service.readOne(spec, this.init(void 0));
|
|
1207
|
+
if (!found) return { actions: [] };
|
|
1208
|
+
return { actions: names(actions.filter((action) => offered(action, found.row))) };
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
/** The live form of an action (its `<Name>Params` type); `null` when it has none or no such action. */
|
|
1212
|
+
async getActionForm(name) {
|
|
1213
|
+
return this.guarded(void 0, async () => {
|
|
1214
|
+
const action = this.actionNamed(name);
|
|
1215
|
+
return action?.info.inputForm ? action.form : null;
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
/** The forms carry their labels: there are no texts served with them. */
|
|
1219
|
+
async getActionFormTexts() {}
|
|
1220
|
+
/**
|
|
1221
|
+
* Runs an action: an operation of the live service bound to the set's type (see `meta().actions`),
|
|
1222
|
+
* its input validated against the action's live form first (`ClientValidationError`). On rows
|
|
1223
|
+
* (`ids`, an array of key objects, as atscript-ui sends them) it is called on the rows of
|
|
1224
|
+
* {@link actionRows}, each row's token as `If-Match` (a `412` on it is that row's
|
|
1225
|
+
* `VersionMismatchError`), several rows as one `$batch` by the live operation's grouping
|
|
1226
|
+
* (`runOperation` of `@atscript/odata`), and answers {@link rowsAnswer}'s summary; a refused
|
|
1227
|
+
* `changeSet` run is its one error, nothing applied. On the collection:
|
|
1228
|
+
* `{ value, message?, messages?, details? }`. No row is filtered by its availability: the
|
|
1229
|
+
* service decides.
|
|
1230
|
+
*/
|
|
1231
|
+
async action(name, id, input) {
|
|
1232
|
+
return this.guarded(void 0, async () => {
|
|
1233
|
+
const action = this.actionNamed(name);
|
|
1234
|
+
if (!action) throw new _atscript_db_client.ActionNotFoundError(name);
|
|
1235
|
+
const params = input ?? {};
|
|
1236
|
+
action.form.validator().validate(params);
|
|
1237
|
+
const { op } = action;
|
|
1238
|
+
const run = {
|
|
1239
|
+
operation: {
|
|
1240
|
+
service: "",
|
|
1241
|
+
operation: op.operation,
|
|
1242
|
+
entitySet: this.entitySet,
|
|
1243
|
+
paramsType: op.type
|
|
1244
|
+
},
|
|
1245
|
+
params
|
|
1246
|
+
};
|
|
1247
|
+
if (action.info.level !== "rows") return callOperation(this.connected().operations, run, this.init(void 0));
|
|
1248
|
+
if (id !== void 0 && !Array.isArray(id)) throw new TypeError(`client.action("${name}"): rows-level actions require an array of identifier objects; received ${shapeOf(id)}.`);
|
|
1249
|
+
const rows = await this.actionRows(action, id ?? []);
|
|
1250
|
+
run.rows = rows;
|
|
1251
|
+
return rowsAnswer(await callOperation(this.connected().operations, run, this.init(void 0)), rows, this.describe().key, (error) => toClientError(error, this.errorContext));
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
geoSearch() {
|
|
1255
|
+
return this.unsupported("geoSearch");
|
|
1256
|
+
}
|
|
1257
|
+
geoPages() {
|
|
1258
|
+
return this.unsupported("geoPages");
|
|
1259
|
+
}
|
|
1260
|
+
actionOnQuery() {
|
|
1261
|
+
return this.unsupported("actionOnQuery");
|
|
1262
|
+
}
|
|
1263
|
+
countActionTarget() {
|
|
1264
|
+
return this.unsupported("countActionTarget");
|
|
1265
|
+
}
|
|
1266
|
+
unsupported(operation) {
|
|
1267
|
+
return Promise.reject(unsupportedOperation(operation, this.entitySet));
|
|
1268
|
+
}
|
|
1269
|
+
/** The db actions of the set: the operations of its service bound to its type. */
|
|
1270
|
+
get actions() {
|
|
1271
|
+
const { operations } = this.connected();
|
|
1272
|
+
this.loadedActions ??= operations ? setActions(operations, this.entitySet, this.url) : [];
|
|
1273
|
+
return this.loadedActions;
|
|
1274
|
+
}
|
|
1275
|
+
actionNamed(name) {
|
|
1276
|
+
return this.actions.find((action) => action.info.name === name);
|
|
1277
|
+
}
|
|
1278
|
+
/** The actions on rows: those `$actions` and `availableActions` judge. */
|
|
1279
|
+
rowActions() {
|
|
1280
|
+
return this.actions.filter((action) => action.info.level === "rows");
|
|
1281
|
+
}
|
|
1282
|
+
/**
|
|
1283
|
+
* `$actions` of a read (atscript-ui asks for it where it shows row actions): every row gets the
|
|
1284
|
+
* names of the row-level actions the live service offers on it, by their availability paths,
|
|
1285
|
+
* as moost-db lists them. The read's `$select` is widened by the paths it does not hold, and
|
|
1286
|
+
* what was read for them alone is taken out of the rows again. Returns what finishes the rows;
|
|
1287
|
+
* they are left as they are when `$actions` is not asked for or the set has no row actions.
|
|
1288
|
+
*/
|
|
1289
|
+
actionHints(spec, controls) {
|
|
1290
|
+
const actions = controls?.$actions ? this.rowActions() : [];
|
|
1291
|
+
if (actions.length === 0) return (rows) => rows;
|
|
1292
|
+
const selected = spec.select;
|
|
1293
|
+
const added = selected ? availabilityPaths(actions).filter((path) => !selected.some((by) => taken(path, by))) : [];
|
|
1294
|
+
if (selected && added.length > 0) spec.select = [...selected, ...added];
|
|
1295
|
+
const drops = added.map((path) => {
|
|
1296
|
+
const top = path.split(".")[0];
|
|
1297
|
+
return selected.some((by) => taken(by, top)) ? { path } : { top };
|
|
1298
|
+
});
|
|
1299
|
+
return (rows) => {
|
|
1300
|
+
for (const row of rows) {
|
|
1301
|
+
row.$actions = names(actions.filter((action) => offered(action, row)));
|
|
1302
|
+
for (const drop of drops) if (drop.top !== void 0) delete row[drop.top];
|
|
1303
|
+
else dropPath(row, drop.path);
|
|
1304
|
+
}
|
|
1305
|
+
return rows;
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* The rows an action on rows is called on, from the ids: each one's key, and for an operation
|
|
1310
|
+
* that writes on a set with a version token its current token, read in one collection read
|
|
1311
|
+
* (the key filter, `$select` of the key), as a Moost server's row load reads it right before the
|
|
1312
|
+
* call. A row that read does not find is a 404, as a Moost server answers an id its row load
|
|
1313
|
+
* does not find (on an action without an availability gate). One id and one row read
|
|
1314
|
+
* is that id's row, whatever literal form the id was written in; several are matched by their
|
|
1315
|
+
* keys as the codec writes them. A set whose reads must filter on another property cannot be
|
|
1316
|
+
* read by key: the runner reads each entity's ETag.
|
|
1317
|
+
*/
|
|
1318
|
+
async actionRows(action, ids) {
|
|
1319
|
+
const { key } = this.describe();
|
|
1320
|
+
const rows = ids.map((id) => {
|
|
1321
|
+
if (id === null || typeof id !== "object" || Array.isArray(id)) throw new TypeError(`client.action("${action.info.name}"): rows-level actions require an array of identifier objects; received an array holding ${shapeOf(id)}.`);
|
|
1322
|
+
return keyOf(id, key, this.entitySet);
|
|
1323
|
+
});
|
|
1324
|
+
const { model } = this.service;
|
|
1325
|
+
if (!this.token || !action.writes || rows.length === 0 || (0, _atscript_odata.demandsOtherFilter)(model, this.entitySet, key)) return rows;
|
|
1326
|
+
const filter = rows.length === 1 ? rows[0] : { $or: rows };
|
|
1327
|
+
const spec = this.spec({
|
|
1328
|
+
filter,
|
|
1329
|
+
controls: { $select: key }
|
|
1330
|
+
});
|
|
1331
|
+
const read = this.rowsOf(await this.service.read(spec, this.init(void 0)));
|
|
1332
|
+
if (rows.length === 1 && read.length === 1) return read;
|
|
1333
|
+
const entityType = model.entitySets[this.entitySet].entityType;
|
|
1334
|
+
const literal = (row) => {
|
|
1335
|
+
try {
|
|
1336
|
+
return (0, _atscript_odata.formatKey)(entityType, row, model, this.service.context);
|
|
1337
|
+
} catch {
|
|
1338
|
+
return;
|
|
1339
|
+
}
|
|
1340
|
+
};
|
|
1341
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
1342
|
+
for (const candidate of read) {
|
|
1343
|
+
const at = literal(candidate);
|
|
1344
|
+
if (at !== void 0 && !byKey.has(at)) byKey.set(at, candidate);
|
|
1345
|
+
}
|
|
1346
|
+
return rows.map((row) => {
|
|
1347
|
+
const wanted = literal(row);
|
|
1348
|
+
const found = wanted === void 0 ? void 0 : byKey.get(wanted);
|
|
1349
|
+
if (!found) throw notFound();
|
|
1350
|
+
return found;
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* Refuses, before anything else, a write the service model does not allow on the set: the
|
|
1355
|
+
* engine's refusal, which the call answers as a Moost server does (`NOT_SUPPORTED`).
|
|
1356
|
+
*/
|
|
1357
|
+
allow(operation) {
|
|
1358
|
+
const refusal = refusalOf(Object.hasOwn(this.service.model.entitySets, this.entitySet) ? this.describe() : void 0, this.entitySet, operation);
|
|
1359
|
+
if (refusal) throw refusal;
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* db-client's write preflight: the type's `@normalize.*` applied, then validated in `mode`
|
|
1363
|
+
* against the metadata's type. What it returns is what is sent.
|
|
1364
|
+
*
|
|
1365
|
+
* @throws ClientValidationError before any call.
|
|
1366
|
+
*/
|
|
1367
|
+
async preflight(data, mode) {
|
|
1368
|
+
const validator = await this.getValidator();
|
|
1369
|
+
const prepared = validator.normalize(data, mode);
|
|
1370
|
+
validator.validate(prepared, mode);
|
|
1371
|
+
return prepared;
|
|
1372
|
+
}
|
|
1373
|
+
asRows(data) {
|
|
1374
|
+
return Array.isArray(data) ? data : [data];
|
|
1375
|
+
}
|
|
1376
|
+
/** The rows of a read, each with its ETag as the version token. */
|
|
1377
|
+
rowsOf(result) {
|
|
1378
|
+
const etags = result.etags ?? [];
|
|
1379
|
+
return result.rows.map((row, i) => this.withToken(row, etags[i]));
|
|
1380
|
+
}
|
|
1381
|
+
/** The row with its ETag in the version token field, when the type has one. */
|
|
1382
|
+
withToken(row, etag) {
|
|
1383
|
+
const { token } = this;
|
|
1384
|
+
if (token && etag !== void 0) row[token] = etag;
|
|
1385
|
+
return row;
|
|
1386
|
+
}
|
|
1387
|
+
withoutToken(row) {
|
|
1388
|
+
const { token } = this;
|
|
1389
|
+
if (!token || !Object.hasOwn(row, token)) return row;
|
|
1390
|
+
const { [token]: _token, ...rest } = row;
|
|
1391
|
+
return rest;
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Runs the write of one row. In an array write a `ClientError` names the row in its paths
|
|
1395
|
+
* (`[2].Country`); the rows before it are written, since OData has no transaction here.
|
|
1396
|
+
*/
|
|
1397
|
+
async row(many, index, run) {
|
|
1398
|
+
try {
|
|
1399
|
+
return await run();
|
|
1400
|
+
} catch (error) {
|
|
1401
|
+
const mapped = toClientError(error, this.errorContext);
|
|
1402
|
+
throw many ? atRow(mapped, index) : mapped;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
/** Update or replace one row or an array of rows, as `Client.update` / `Client.replace` do. */
|
|
1406
|
+
changeAll(mode, data, opts) {
|
|
1407
|
+
return this.guarded(opts, async (call) => {
|
|
1408
|
+
this.allow(mode);
|
|
1409
|
+
const members = membersOf(this.service.model, this.entitySet);
|
|
1410
|
+
const patch = mode === "update";
|
|
1411
|
+
const many = Array.isArray(data);
|
|
1412
|
+
if (many) this.single(call, mode);
|
|
1413
|
+
const prepared = (many ? data : [data]).map((item, index) => {
|
|
1414
|
+
const at = many ? `[${index}].` : "";
|
|
1415
|
+
const { row, version } = versionOf(item, this.token, at);
|
|
1416
|
+
return {
|
|
1417
|
+
row: writableRow(row, members, patch, at),
|
|
1418
|
+
version
|
|
1419
|
+
};
|
|
1420
|
+
});
|
|
1421
|
+
const translated = many ? prepared.map((item) => item.row) : prepared[0].row;
|
|
1422
|
+
const rows = this.asRows(await this.preflight(translated, patch ? "patch" : "replace"));
|
|
1423
|
+
const key = this.describe().key;
|
|
1424
|
+
const targets = rows.map((row, index) => {
|
|
1425
|
+
return {
|
|
1426
|
+
key: keyOf(row, key, this.entitySet, many ? `[${index}].` : ""),
|
|
1427
|
+
body: patch ? withoutKey(row, key) : row,
|
|
1428
|
+
version: prepared[index].version
|
|
1429
|
+
};
|
|
1430
|
+
});
|
|
1431
|
+
const total = {
|
|
1432
|
+
matchedCount: 0,
|
|
1433
|
+
modifiedCount: 0
|
|
1434
|
+
};
|
|
1435
|
+
for (const [index, target] of targets.entries()) {
|
|
1436
|
+
const { key: identity, body, version } = target;
|
|
1437
|
+
const counted = await this.row(many, index, () => version === void 0 ? this.changeOne(mode, identity, body, call) : this.changeAt(mode, {
|
|
1438
|
+
key: identity,
|
|
1439
|
+
body,
|
|
1440
|
+
version,
|
|
1441
|
+
many
|
|
1442
|
+
}, call));
|
|
1443
|
+
total.matchedCount += counted.matchedCount;
|
|
1444
|
+
total.modifiedCount += counted.modifiedCount;
|
|
1445
|
+
}
|
|
1446
|
+
return total;
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* Update or replace one entity, answering what moost-db answers: `{ 1, 1 }` when it was
|
|
1451
|
+
* written, `{ 0, 0 }` when it does not exist, `{ 1, 0 }` when there was nothing to write (only
|
|
1452
|
+
* the key, or only read-only members the engine drops) and the entity exists.
|
|
1453
|
+
*
|
|
1454
|
+
* Without the caller's version token ({@link changeAt} has it) the write is last-write-wins.
|
|
1455
|
+
* Where the entity set declares optimistic concurrency, the entity's current ETag is read right
|
|
1456
|
+
* before the write and sent as `If-Match`, which satisfies the service's If-Match requirement
|
|
1457
|
+
* and nothing more: a change made since the caller read the row is overwritten. A `412` (a
|
|
1458
|
+
* change between the pre-read and the write) has the ETag read again and the write sent again,
|
|
1459
|
+
* three attempts in all (`changeByKey`), as a Moost server writes; the last one's `412` is a
|
|
1460
|
+
* `ClientError` 503 `SERIALIZATION_FAILURE`.
|
|
1461
|
+
*/
|
|
1462
|
+
async changeOne(mode, key, body, opts) {
|
|
1463
|
+
const { matched, modified } = await (0, _atscript_odata.changeByKey)(this.sender(mode, key, body, opts), this.byKey(key, opts));
|
|
1464
|
+
return {
|
|
1465
|
+
matchedCount: matched ? 1 : 0,
|
|
1466
|
+
modifiedCount: modified ? 1 : 0
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Update or replace one entity on the condition that it still has the caller's version token
|
|
1471
|
+
* (its ETag when the caller read it), sent as `If-Match`; nothing is read first. With nothing to
|
|
1472
|
+
* send, the token is compared with the entity's current one. A write that matches nothing (a
|
|
1473
|
+
* `412`: the entity changed; a missing entity; a token that is not the current one) is
|
|
1474
|
+
* {@link unmatched}.
|
|
1475
|
+
*/
|
|
1476
|
+
async changeAt(mode, target, opts) {
|
|
1477
|
+
const { key, body, version, many } = target;
|
|
1478
|
+
const { matched, modified, current } = await (0, _atscript_odata.changeByKey)(this.sender(mode, key, body, opts), {
|
|
1479
|
+
...this.byKey(key, opts),
|
|
1480
|
+
etag: version
|
|
1481
|
+
});
|
|
1482
|
+
if (matched) return {
|
|
1483
|
+
matchedCount: 1,
|
|
1484
|
+
modifiedCount: modified ? 1 : 0
|
|
1485
|
+
};
|
|
1486
|
+
const known = current === void 0 ? void 0 : {
|
|
1487
|
+
found: current !== null,
|
|
1488
|
+
...current
|
|
1489
|
+
};
|
|
1490
|
+
return this.unmatched(key, many, opts, known);
|
|
1491
|
+
}
|
|
1492
|
+
/** The update or replace of one entity, sent with an ETag as `If-Match`; an empty patch is skipped. */
|
|
1493
|
+
sender(mode, key, body, opts) {
|
|
1494
|
+
if (mode === "update" && Object.keys(body).length === 0) return () => Promise.resolve({ skipped: true });
|
|
1495
|
+
return (etag) => this.engine(opts)[mode](this.entitySet, key, body, this.writeInit(opts, void 0, etag));
|
|
1496
|
+
}
|
|
1497
|
+
/**
|
|
1498
|
+
* How a write by key reads the entity (`changeByKey` of `@atscript/odata`): the whole entity,
|
|
1499
|
+
* for its ETag, read right before a write without the caller's token where the entity set
|
|
1500
|
+
* declares optimistic concurrency, and for its existence after a write with nothing to send.
|
|
1501
|
+
*/
|
|
1502
|
+
byKey(key, opts) {
|
|
1503
|
+
return {
|
|
1504
|
+
read: async () => {
|
|
1505
|
+
const current = await this.currentETag(key, opts);
|
|
1506
|
+
return current.found ? { etag: current.etag } : void 0;
|
|
1507
|
+
},
|
|
1508
|
+
readEtag: this.etags
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
/**
|
|
1512
|
+
* A write with the caller's version token that matched nothing, as moost-db answers it: `{ 0, 0 }`
|
|
1513
|
+
* for a row of an array; alone, by the entity as it is now (read unless `current` has it): a 404
|
|
1514
|
+
* `NOT_FOUND` when it is gone, else a `VersionMismatchError` with its current token.
|
|
1515
|
+
*/
|
|
1516
|
+
async unmatched(key, many, opts, current) {
|
|
1517
|
+
if (many) return {
|
|
1518
|
+
matchedCount: 0,
|
|
1519
|
+
modifiedCount: 0
|
|
1520
|
+
};
|
|
1521
|
+
const { found, etag } = current ?? await this.currentETag(key, opts);
|
|
1522
|
+
if (!found) throw notFound();
|
|
1523
|
+
throw versionMismatch(etag);
|
|
1524
|
+
}
|
|
1525
|
+
/** Reads the entity for its ETag: whether it exists, and the ETag it has now, if any. */
|
|
1526
|
+
async currentETag(key, opts) {
|
|
1527
|
+
const current = await this.service.readOne({
|
|
1528
|
+
...this.spec(void 0),
|
|
1529
|
+
key
|
|
1530
|
+
}, this.init(opts));
|
|
1531
|
+
return current ? {
|
|
1532
|
+
found: true,
|
|
1533
|
+
etag: current.etag
|
|
1534
|
+
} : { found: false };
|
|
1535
|
+
}
|
|
1536
|
+
/** The options of one write: the session, signal and headers of the client's calls. */
|
|
1537
|
+
writeInit(opts, write, etag) {
|
|
1538
|
+
const { session, signal, headers, batch } = this.init(opts);
|
|
1539
|
+
const init = {};
|
|
1540
|
+
if (session) init.session = session;
|
|
1541
|
+
if (signal) init.signal = signal;
|
|
1542
|
+
if (headers) init.headers = headers;
|
|
1543
|
+
if (batch === false) init.batch = false;
|
|
1544
|
+
if (write) init.write = write;
|
|
1545
|
+
if (etag !== void 0) init.etag = etag;
|
|
1546
|
+
return init;
|
|
1547
|
+
}
|
|
1548
|
+
/**
|
|
1549
|
+
* Runs a call and rethrows what the engine throws as db-client's errors. A call given
|
|
1550
|
+
* `{ batch }` holds that batch back from its start until its request is queued (through
|
|
1551
|
+
* {@link engine}) or it settles; `run` gets the options with its ticket.
|
|
1552
|
+
*/
|
|
1553
|
+
guarded(opts, run) {
|
|
1554
|
+
let ticket;
|
|
1555
|
+
try {
|
|
1556
|
+
ticket = joinBatch(opts?.batch);
|
|
1557
|
+
} catch (error) {
|
|
1558
|
+
return Promise.reject(error);
|
|
1559
|
+
}
|
|
1560
|
+
const call = ticket ? {
|
|
1561
|
+
...opts,
|
|
1562
|
+
[TICKET]: ticket
|
|
1563
|
+
} : opts;
|
|
1564
|
+
const promise = (async () => {
|
|
1565
|
+
try {
|
|
1566
|
+
await this.ready();
|
|
1567
|
+
return await run(call);
|
|
1568
|
+
} catch (error) {
|
|
1569
|
+
throw toClientError(error, this.errorContext);
|
|
1570
|
+
} finally {
|
|
1571
|
+
ticket?.release();
|
|
1572
|
+
}
|
|
1573
|
+
})();
|
|
1574
|
+
ticket?.track(promise);
|
|
1575
|
+
return promise;
|
|
1576
|
+
}
|
|
1577
|
+
/**
|
|
1578
|
+
* The methods the call's own request goes through: the batch it was given, once (a pre-read
|
|
1579
|
+
* before it uses the service); the service otherwise, auto-batched unless `batch: false`.
|
|
1580
|
+
*/
|
|
1581
|
+
engine(call) {
|
|
1582
|
+
return call?.[TICKET]?.take(this.service) ?? this.service;
|
|
1583
|
+
}
|
|
1584
|
+
/**
|
|
1585
|
+
* Refuses an array write given a batch: its rows go out on their own (an insert as a `$batch` of
|
|
1586
|
+
* its own, an update or replace one after the other).
|
|
1587
|
+
*/
|
|
1588
|
+
single(call, method) {
|
|
1589
|
+
if (call?.[TICKET]) throw new TypeError(`client.${method}([...]) cannot join a batch: its rows go out on their own${method === "insert" ? ", as a $batch of their own" : ", one after the other"}. Give each row its own call.`);
|
|
1590
|
+
}
|
|
1591
|
+
/** What the entity set allows, as the query layer judges it (the target is settled once). */
|
|
1592
|
+
describe() {
|
|
1593
|
+
this.described ??= (0, _atscript_odata.describeEntitySet)(this.service.model, this.entitySet, this.service.context);
|
|
1594
|
+
return this.described;
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* Whether the entity set declares optimistic concurrency (`Core.OptimisticConcurrency`, v2
|
|
1598
|
+
* `ConcurrencyMode="Fixed"`), so that the service requires `If-Match` on a write. An empty
|
|
1599
|
+
* property list declares it too: the ETag is in use, its properties are not named.
|
|
1600
|
+
*/
|
|
1601
|
+
get etags() {
|
|
1602
|
+
return this.describe().optimisticConcurrency !== void 0;
|
|
1603
|
+
}
|
|
1604
|
+
spec(query) {
|
|
1605
|
+
const spec = (0, _atscript_odata.readSpecFromUniquery)(this.entitySet, query, {
|
|
1606
|
+
model: this.service.model,
|
|
1607
|
+
ignoreControls: IGNORED_CONTROLS
|
|
1608
|
+
});
|
|
1609
|
+
const { token } = this;
|
|
1610
|
+
if (token && spec.select) spec.select = spec.select.filter((path) => path !== token);
|
|
1611
|
+
return spec;
|
|
1612
|
+
}
|
|
1613
|
+
/**
|
|
1614
|
+
* Orders a read exactly as an atscript-db backend over the same service does, so both hosts
|
|
1615
|
+
* return the same rows on the same page:
|
|
1616
|
+
*
|
|
1617
|
+
* - a sort gets the key properties it leaves out appended in key order, in the direction of
|
|
1618
|
+
* its last key (`price desc` reads `price desc, id desc`), as the atscript-db core does for
|
|
1619
|
+
* every row read; a sort that names the whole key is left as it is;
|
|
1620
|
+
* - without a sort, a page (`paged`) comes in key order, ascending, as moost-db's `/pages`
|
|
1621
|
+
* returns it, unless it is a free-text search, which keeps the order of the service;
|
|
1622
|
+
* - without a sort, any other read keeps the order of the service.
|
|
1623
|
+
*
|
|
1624
|
+
* Only key properties the entity set can sort by are used.
|
|
1625
|
+
*/
|
|
1626
|
+
stableOrder(spec, paged) {
|
|
1627
|
+
const orderBy = spec.orderBy ?? [];
|
|
1628
|
+
const { sortableKey } = this.describe();
|
|
1629
|
+
if (orderBy.length === 0) {
|
|
1630
|
+
if (paged && spec.search === void 0 && sortableKey.length > 0) spec.orderBy = sortableKey.map((path) => ({ path }));
|
|
1631
|
+
return spec;
|
|
1632
|
+
}
|
|
1633
|
+
const missing = sortableKey.filter((key) => !orderBy.some((entry) => entry.path === key));
|
|
1634
|
+
if (missing.length === 0) return spec;
|
|
1635
|
+
const desc = orderBy.at(-1).desc === true;
|
|
1636
|
+
spec.orderBy = [...orderBy, ...missing.map((path) => desc ? {
|
|
1637
|
+
path,
|
|
1638
|
+
desc
|
|
1639
|
+
} : { path })];
|
|
1640
|
+
return spec;
|
|
1641
|
+
}
|
|
1642
|
+
/** What a count is taken over: the filter, and the search term when there is one. */
|
|
1643
|
+
countSpec(query) {
|
|
1644
|
+
const search = (query?.controls)?.$search;
|
|
1645
|
+
return this.spec({
|
|
1646
|
+
filter: query?.filter,
|
|
1647
|
+
controls: search === void 0 ? {} : { $search: search }
|
|
1648
|
+
});
|
|
1649
|
+
}
|
|
1650
|
+
/** The key of one entity from what `one()` takes: a key object, or the value of a single key. */
|
|
1651
|
+
key(id) {
|
|
1652
|
+
if (id !== null && typeof id === "object" && !Array.isArray(id) && !(id instanceof Date)) return id;
|
|
1653
|
+
const { key } = this.describe();
|
|
1654
|
+
if (key.length !== 1 || id === void 0 || id === null || Array.isArray(id)) throw new _atscript_odata.ODataQueryError("INVALID_KEY", key.length === 1 ? `${this.entitySet}: no key value given` : `${this.entitySet} is identified by ${key.join(", ") || "no key"}: pass an object with these properties`);
|
|
1655
|
+
return { [key[0]]: id };
|
|
1656
|
+
}
|
|
1657
|
+
init(opts) {
|
|
1658
|
+
const locale = typeof this.locale === "function" ? this.locale() : this.locale;
|
|
1659
|
+
return callInit(this.callDefaults, this.service, opts, locale);
|
|
1660
|
+
}
|
|
1661
|
+
};
|
|
1662
|
+
const ODataClient = ODataEntityClient;
|
|
1663
|
+
//#endregion
|
|
1664
|
+
//#region src/factory.ts
|
|
1665
|
+
/** The URL prefix OData entity sets are addressed under unless the factory is given another. */
|
|
1666
|
+
const DEFAULT_ODATA_PREFIX = "/odata";
|
|
1667
|
+
const HTTP_PATH = "db.http.path";
|
|
1668
|
+
/** The key of a target among those of its registration: the URL segments after the name. */
|
|
1669
|
+
function targetKey(entitySet, valueHelpService) {
|
|
1670
|
+
return valueHelpService === void 0 ? entitySet : `${valueHelpService}\u0000${entitySet}`;
|
|
1671
|
+
}
|
|
1672
|
+
/**
|
|
1673
|
+
* The entity set types of a service, with the engine each is read through: the service, or for a
|
|
1674
|
+
* type of a value-help service (`@odata.valueHelpService`) the engine of that service.
|
|
1675
|
+
*/
|
|
1676
|
+
function entitySetTypes(name, service, source) {
|
|
1677
|
+
if ("plan" in source && typeof source.types === "object" && source.types !== null && !(0, _atscript_typescript_utils.isAnnotatedType)(source.types)) source = source.types;
|
|
1678
|
+
const types = /* @__PURE__ */ new Map();
|
|
1679
|
+
for (const candidate of Object.values(source)) {
|
|
1680
|
+
if (!(0, _atscript_typescript_utils.isAnnotatedType)(candidate)) continue;
|
|
1681
|
+
const metadata = candidate.metadata;
|
|
1682
|
+
const entitySet = metadata.get("db.table");
|
|
1683
|
+
if (typeof entitySet !== "string") continue;
|
|
1684
|
+
const declared = metadata.get("odata.valueHelpService");
|
|
1685
|
+
const valueHelpService = typeof declared === "string" ? declared : void 0;
|
|
1686
|
+
const engine = valueHelpService === void 0 ? service : service.valueHelpService(valueHelpService);
|
|
1687
|
+
if (!engine) throw new Error(`Service "${name}": the type "${candidate.id ?? entitySet}" is of value-help service "${valueHelpService}", which the service model does not have. Create the service from the model module generated with the types, which holds its value-help services.`);
|
|
1688
|
+
if (!Object.hasOwn(engine.model.entitySets, entitySet)) throw new Error(`Service "${name}": the type "${candidate.id ?? entitySet}" is for entity set "${entitySet}", which the service model does not have. Were the types generated from another service?`);
|
|
1689
|
+
const key = targetKey(entitySet, valueHelpService);
|
|
1690
|
+
const known = types.get(key);
|
|
1691
|
+
if (known && known.type !== candidate) throw new Error(`Service "${name}": two types are registered for entity set "${entitySet}"`);
|
|
1692
|
+
types.set(key, {
|
|
1693
|
+
service: engine,
|
|
1694
|
+
entitySet,
|
|
1695
|
+
valueHelpService,
|
|
1696
|
+
type: candidate,
|
|
1697
|
+
url: ""
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
return types;
|
|
1701
|
+
}
|
|
1702
|
+
/** The declarations of a fixed registration's types: the operation types among them. */
|
|
1703
|
+
function declarationsOf(source) {
|
|
1704
|
+
const built = "plan" in source && typeof source.types === "object" && source.types !== null;
|
|
1705
|
+
const types = {};
|
|
1706
|
+
for (const [name, value] of Object.entries(built ? source.types : source)) if ((0, _atscript_typescript_utils.isAnnotatedType)(value)) types[name] = value;
|
|
1707
|
+
return built ? {
|
|
1708
|
+
types,
|
|
1709
|
+
plan: source.plan
|
|
1710
|
+
} : { types };
|
|
1711
|
+
}
|
|
1712
|
+
function isFixed(registration) {
|
|
1713
|
+
return "service" in registration && registration.service !== void 0;
|
|
1714
|
+
}
|
|
1715
|
+
/**
|
|
1716
|
+
* Creates the client factory atscript-ui routes through. A URL of the form
|
|
1717
|
+
* `<prefix>/<serviceName>/<EntitySet>` gets a {@link ODataClient} for that entity set; every other
|
|
1718
|
+
* URL goes to `fallback`.
|
|
1719
|
+
*
|
|
1720
|
+
* A live service ({@link LiveServiceRegistration}) is read on the first call of any of its
|
|
1721
|
+
* clients, or by `connect()`: its `$metadata` and value-help documents, in the language the
|
|
1722
|
+
* models were saved in, and its generated module's classes become the live declarations. Until
|
|
1723
|
+
* then a URL of the service gets a client that connects first; an entity set the live service
|
|
1724
|
+
* does not have answers every call with a `ClientError` 404 (`NOT_FOUND`), moost-db's body, as a
|
|
1725
|
+
* Moost server answers it. A failed read is not kept: the next call reads again.
|
|
1726
|
+
*
|
|
1727
|
+
* Once a service's types are known, the factory writes each entity set's URL into its type as
|
|
1728
|
+
* `db.http.path`. That is how atscript-ui finds the target of a foreign key or of a
|
|
1729
|
+
* `@ui.valueHelp` binding, both in a served `/meta` type and in a compiled type used directly. A
|
|
1730
|
+
* type can carry one URL only: a type object registered with a second factory under another
|
|
1731
|
+
* prefix or service name is re-pointed to that one.
|
|
1732
|
+
*
|
|
1733
|
+
* The calls of a live service's clients are auto-batched: those of one synchronous pass go out as
|
|
1734
|
+
* one `$batch` (see {@link LiveServiceRegistration}); `createBatch()` groups calls on purpose.
|
|
1735
|
+
*
|
|
1736
|
+
* The entity set types of the value-help services of a registered service (generated from its
|
|
1737
|
+
* `Common.ValueListReferences` documents, `@odata.valueHelpService`) are registered with it: a
|
|
1738
|
+
* URL `<prefix>/<serviceName>/<valueHelpService>/<EntitySet>` (each segment URI-encoded) gets a
|
|
1739
|
+
* client that reads the set at the value-help service's root, through
|
|
1740
|
+
* `service.valueHelpService(…)`, with the session of the registered service.
|
|
1741
|
+
*
|
|
1742
|
+
* @throws Error for a service registered twice, and for fixed types that do not belong to the
|
|
1743
|
+
* service they are registered with.
|
|
1744
|
+
*/
|
|
1745
|
+
function createODataClientFactory(options) {
|
|
1746
|
+
const prefix = (options.prefix ?? "/odata").replace(/\/+$/, "");
|
|
1747
|
+
const fallback = options.fallback ?? ((url, callOptions) => new _atscript_db_client.Client(url, callOptions));
|
|
1748
|
+
const sendLocale = options.locale !== "ignore";
|
|
1749
|
+
const registered = /* @__PURE__ */ new Map();
|
|
1750
|
+
const urlFor = (name, entitySet, valueHelpService) => [prefix, ...[
|
|
1751
|
+
name,
|
|
1752
|
+
valueHelpService ?? [],
|
|
1753
|
+
entitySet
|
|
1754
|
+
].flat().map(encodeURIComponent)].join("/");
|
|
1755
|
+
/** The targets of a service's types, with their URLs written into the types. */
|
|
1756
|
+
const targetsOf = (name, service, types) => {
|
|
1757
|
+
const targets = entitySetTypes(name, service, types);
|
|
1758
|
+
for (const target of targets.values()) {
|
|
1759
|
+
const { entitySet, valueHelpService, type } = target;
|
|
1760
|
+
target.url = urlFor(name, entitySet, valueHelpService);
|
|
1761
|
+
const metadata = type.metadata;
|
|
1762
|
+
if (metadata.get(HTTP_PATH) !== target.url) metadata.set(HTTP_PATH, target.url);
|
|
1763
|
+
if (valueHelpService !== void 0) shareSession(target.service, sharedSession(service));
|
|
1764
|
+
}
|
|
1765
|
+
return targets;
|
|
1766
|
+
};
|
|
1767
|
+
for (const registration of options.services) {
|
|
1768
|
+
let entry;
|
|
1769
|
+
if (isFixed(registration)) {
|
|
1770
|
+
entry = {
|
|
1771
|
+
name: registration.name,
|
|
1772
|
+
targets: targetsOf(registration.name, registration.service, registration.types)
|
|
1773
|
+
};
|
|
1774
|
+
entry.connection = {
|
|
1775
|
+
name: entry.name,
|
|
1776
|
+
service: registration.service,
|
|
1777
|
+
...declarationsOf(registration.types),
|
|
1778
|
+
fast: true
|
|
1779
|
+
};
|
|
1780
|
+
} else {
|
|
1781
|
+
const { onDrift: _onDrift, verdicts: _verdicts, batch, ...live } = registration;
|
|
1782
|
+
const source = (0, _atscript_odata.createODataSource)({
|
|
1783
|
+
...live,
|
|
1784
|
+
batch: batch === false ? false : {
|
|
1785
|
+
auto: true,
|
|
1786
|
+
...batch
|
|
1787
|
+
}
|
|
1788
|
+
});
|
|
1789
|
+
entry = {
|
|
1790
|
+
name: source.name,
|
|
1791
|
+
source
|
|
1792
|
+
};
|
|
1793
|
+
}
|
|
1794
|
+
if (registered.has(entry.name)) throw new Error(`Service "${entry.name}" is registered twice`);
|
|
1795
|
+
registered.set(entry.name, entry);
|
|
1796
|
+
}
|
|
1797
|
+
/** Connects a live service and finds its targets; a fixed one has them. */
|
|
1798
|
+
async function connected(entry) {
|
|
1799
|
+
if (entry.targets) return entry.targets;
|
|
1800
|
+
let connection;
|
|
1801
|
+
try {
|
|
1802
|
+
connection = await entry.source.connect();
|
|
1803
|
+
} catch (error) {
|
|
1804
|
+
const mapped = toClientError(error);
|
|
1805
|
+
throw mapped === error ? new _atscript_db_client.TransportError("GET", `${entry.name}/$metadata`, error instanceof Error ? error.message : String(error), error) : mapped;
|
|
1806
|
+
}
|
|
1807
|
+
entry.targets ??= targetsOf(entry.name, connection.service, connection.types);
|
|
1808
|
+
entry.connection = connection;
|
|
1809
|
+
return entry.targets;
|
|
1810
|
+
}
|
|
1811
|
+
const find = (url) => {
|
|
1812
|
+
if (!url.startsWith(`${prefix}/`)) return void 0;
|
|
1813
|
+
const segments = url.slice(prefix.length + 1).replace(/\/+$/, "").split("/");
|
|
1814
|
+
if (segments.length !== 2 && segments.length !== 3) return void 0;
|
|
1815
|
+
let decoded;
|
|
1816
|
+
try {
|
|
1817
|
+
decoded = segments.map((segment) => decodeURIComponent(segment));
|
|
1818
|
+
} catch {
|
|
1819
|
+
return;
|
|
1820
|
+
}
|
|
1821
|
+
const [name, ...rest] = decoded;
|
|
1822
|
+
const entry = registered.get(name);
|
|
1823
|
+
if (!entry) return void 0;
|
|
1824
|
+
const entitySet = rest.at(-1);
|
|
1825
|
+
const valueHelpService = rest.length === 2 ? rest[0] : void 0;
|
|
1826
|
+
if (entry.targets && !entry.targets.has(targetKey(entitySet, valueHelpService))) return void 0;
|
|
1827
|
+
return valueHelpService === void 0 ? {
|
|
1828
|
+
entry,
|
|
1829
|
+
entitySet
|
|
1830
|
+
} : {
|
|
1831
|
+
entry,
|
|
1832
|
+
entitySet,
|
|
1833
|
+
valueHelpService
|
|
1834
|
+
};
|
|
1835
|
+
};
|
|
1836
|
+
const factory = ((url, callOptions) => {
|
|
1837
|
+
const found = find(url);
|
|
1838
|
+
if (!found) return callOptions === void 0 ? fallback(url) : fallback(url, callOptions);
|
|
1839
|
+
const { entry, entitySet, valueHelpService } = found;
|
|
1840
|
+
const key = targetKey(entitySet, valueHelpService);
|
|
1841
|
+
const common = {
|
|
1842
|
+
entitySet,
|
|
1843
|
+
url: urlFor(entry.name, entitySet, valueHelpService),
|
|
1844
|
+
locale: sendLocale ? callOptions?.locale : void 0,
|
|
1845
|
+
queryLimit: options.queryLimit,
|
|
1846
|
+
call: options.call
|
|
1847
|
+
};
|
|
1848
|
+
const clientTarget = (target) => ({
|
|
1849
|
+
service: target.service,
|
|
1850
|
+
type: target.type,
|
|
1851
|
+
operations: target.valueHelpService === void 0 ? entry.connection : void 0
|
|
1852
|
+
});
|
|
1853
|
+
const known = entry.targets?.get(key);
|
|
1854
|
+
if (known) return new ODataClient({
|
|
1855
|
+
...common,
|
|
1856
|
+
...clientTarget(known)
|
|
1857
|
+
});
|
|
1858
|
+
return new ODataClient({
|
|
1859
|
+
...common,
|
|
1860
|
+
connect: async () => {
|
|
1861
|
+
const target = (await connected(entry)).get(key);
|
|
1862
|
+
if (!target) throw notFound();
|
|
1863
|
+
return clientTarget(target);
|
|
1864
|
+
}
|
|
1865
|
+
});
|
|
1866
|
+
});
|
|
1867
|
+
factory.urlOf = (service, entitySet, valueHelpService) => {
|
|
1868
|
+
const entry = registered.get(service);
|
|
1869
|
+
if (!entry) return void 0;
|
|
1870
|
+
if (!entry.targets) return urlFor(service, entitySet, valueHelpService);
|
|
1871
|
+
return entry.targets.get(targetKey(entitySet, valueHelpService))?.url;
|
|
1872
|
+
};
|
|
1873
|
+
factory.resolve = (url) => {
|
|
1874
|
+
const found = find(url);
|
|
1875
|
+
if (!found) return void 0;
|
|
1876
|
+
const { entry, entitySet, valueHelpService } = found;
|
|
1877
|
+
return valueHelpService === void 0 ? {
|
|
1878
|
+
service: entry.name,
|
|
1879
|
+
entitySet
|
|
1880
|
+
} : {
|
|
1881
|
+
service: entry.name,
|
|
1882
|
+
entitySet,
|
|
1883
|
+
valueHelpService
|
|
1884
|
+
};
|
|
1885
|
+
};
|
|
1886
|
+
factory.call = (async (operation, input = {}, opts) => {
|
|
1887
|
+
let service;
|
|
1888
|
+
if (typeof operation === "string") {
|
|
1889
|
+
if (registered.size !== 1) throw new Error(`call("${operation}"): ${registered.size} services are registered; name one: { service, operation }`);
|
|
1890
|
+
service = [...registered.keys()][0];
|
|
1891
|
+
} else service = operation.service;
|
|
1892
|
+
const entry = registered.get(service);
|
|
1893
|
+
if (!entry) throw new Error(`No service "${service}" is registered`);
|
|
1894
|
+
await connected(entry);
|
|
1895
|
+
const connection = entry.connection;
|
|
1896
|
+
const { params, extra, row, entitySet } = input;
|
|
1897
|
+
const run = {
|
|
1898
|
+
...typeof operation === "string" ? {
|
|
1899
|
+
operation,
|
|
1900
|
+
entitySet
|
|
1901
|
+
} : "paramsType" in operation ? { operation } : {
|
|
1902
|
+
operation: operation.operation,
|
|
1903
|
+
entitySet: operation.entitySet
|
|
1904
|
+
},
|
|
1905
|
+
...row ? { rows: [row] } : {},
|
|
1906
|
+
...params ? { params } : {},
|
|
1907
|
+
...extra ? { extra } : {}
|
|
1908
|
+
};
|
|
1909
|
+
const locale = sendLocale ? opts?.locale : void 0;
|
|
1910
|
+
const init = callInit(options.call ?? {}, connection.service, opts, locale);
|
|
1911
|
+
try {
|
|
1912
|
+
const answer = await callOperation(connection, run, init);
|
|
1913
|
+
return row ? {
|
|
1914
|
+
...answer,
|
|
1915
|
+
value: answer.value[0]
|
|
1916
|
+
} : answer;
|
|
1917
|
+
} catch (error) {
|
|
1918
|
+
const entitySet = runEntitySet(run);
|
|
1919
|
+
throw toClientError(error, {
|
|
1920
|
+
model: connection.service.model,
|
|
1921
|
+
entitySet
|
|
1922
|
+
});
|
|
1923
|
+
}
|
|
1924
|
+
});
|
|
1925
|
+
factory.createBatch = (service) => {
|
|
1926
|
+
if (service === void 0 && registered.size !== 1) throw new Error(`createBatch(): ${registered.size} services are registered; name the one the batch is of`);
|
|
1927
|
+
const name = service ?? [...registered.keys()][0];
|
|
1928
|
+
const entry = registered.get(name);
|
|
1929
|
+
if (!entry) throw new Error(`No service "${name}" is registered`);
|
|
1930
|
+
return createClientBatch(name, () => entry.connection?.service);
|
|
1931
|
+
};
|
|
1932
|
+
factory.connect = async (service) => {
|
|
1933
|
+
const entries = service === void 0 ? [...registered.values()] : [registered.get(service)];
|
|
1934
|
+
if (entries.some((entry) => !entry)) throw new Error(`No service "${service}" is registered`);
|
|
1935
|
+
await Promise.all(entries.map((entry) => connected(entry)));
|
|
1936
|
+
return Object.fromEntries(entries.map((entry) => [entry.name, entry.connection]));
|
|
1937
|
+
};
|
|
1938
|
+
return factory;
|
|
1939
|
+
}
|
|
1940
|
+
//#endregion
|
|
1941
|
+
exports.DEFAULT_ODATA_PREFIX = DEFAULT_ODATA_PREFIX;
|
|
1942
|
+
exports.DEFAULT_QUERY_LIMIT = DEFAULT_QUERY_LIMIT;
|
|
1943
|
+
exports.ODataClient = ODataClient;
|
|
1944
|
+
exports.buildMeta = buildMeta;
|
|
1945
|
+
exports.createODataClientFactory = createODataClientFactory;
|
|
1946
|
+
exports.messagePath = messagePath;
|
|
1947
|
+
exports.toClientError = toClientError;
|
|
1948
|
+
exports.unsupportedOperation = unsupportedOperation;
|