@atscript/moost-odata 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 +560 -2
- package/dist/index.cjs +700 -0
- package/dist/index.d.cts +401 -0
- package/dist/index.d.mts +402 -0
- package/dist/index.mjs +681 -0
- package/package.json +71 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Artem Maltsev <artem@maltsev.nl>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,561 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://odata.atscript.dev/logo.svg" alt="Atscript" width="120" />
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<h1 align="center">@atscript/moost-odata</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
Moost integration for serving OData services as Atscript DB controllers.
|
|
9
|
+
</p>
|
|
10
|
+
|
|
11
|
+
<p align="center">
|
|
12
|
+
Part of Atscript OData. Works with SAP S/4HANA®, SAP Gateway and SAP RAP services, and with any standard OData v2/v4 service.
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
<p align="center">
|
|
16
|
+
<a href="https://odata.atscript.dev">Documentation</a>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
> Preview release (0.0.x) — APIs may still change between releases. The controllers serve queries, pages, single entities,
|
|
22
|
+
> `/meta` and, where the service allows them, single-entity writes, with conflict detection when
|
|
23
|
+
> the client sends back the row's version token (see [Writes](#writes)), and the service's
|
|
24
|
+
> operations through generated bases (see [Operations](#operations)).
|
|
25
|
+
|
|
26
|
+
A Moost server re-serves an OData v2 / v4 service through the REST controllers of
|
|
27
|
+
[`@atscript/moost-db`](https://db.atscript.dev), so a browser sees a plain atscript-db backend.
|
|
28
|
+
[`@atscript/db-odata`](https://www.npmjs.com/package/@atscript/db-odata) is the database adapter. You declare the controllers yourself,
|
|
29
|
+
one per entity set, exactly as with any moost-db controller; this package gives you:
|
|
30
|
+
|
|
31
|
+
- **base classes** for those controllers, `ODataReadableController` and `ODataTableController`, which
|
|
32
|
+
offer only what the entity set can do and answer a set gone live `404`;
|
|
33
|
+
- **operations**: function imports and actions as moost-db db actions of generated bases you
|
|
34
|
+
extend, and unbound ones as POST routes of a generated operations base (`ODataOperation`,
|
|
35
|
+
`ODataOperationsController`);
|
|
36
|
+
- **value-help controllers**, `valueHelpControllers`: the read-only controllers of the sets your
|
|
37
|
+
value helps target, made from the live types, so every field gets its picker;
|
|
38
|
+
- **credentials strategies** for the space's `init`: the credentials the server was given for the
|
|
39
|
+
service (a technical user), a time limit.
|
|
40
|
+
|
|
41
|
+
Typed at build time, live at runtime: the controllers are declared over the generated types, and
|
|
42
|
+
`space.connect()` reads the live `$metadata` before the app starts.
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pnpm add @atscript/moost-odata @atscript/db-odata @atscript/odata \
|
|
48
|
+
@atscript/moost-db @atscript/db @atscript/typescript @uniqu/core \
|
|
49
|
+
moost @moostjs/event-http @wooksjs/event-core @wooksjs/event-http @wooksjs/http-body
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Needs `@atscript/db` and `@atscript/moost-db` 0.1.200 or newer, `@atscript/typescript` 0.2.25 or
|
|
53
|
+
newer, Moost 0.7.12 or newer and Wooks 0.8.8 or newer.
|
|
54
|
+
|
|
55
|
+
The models come from the generator of `@atscript/odata`: see the
|
|
56
|
+
[installation guide](https://odata.atscript.dev/guide/installation). Every export is documented in the
|
|
57
|
+
[API reference](https://odata.atscript.dev/api/moost-odata).
|
|
58
|
+
|
|
59
|
+
## Quick start
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
// server/main.ts
|
|
63
|
+
import { createODataSpace } from "@atscript/db-odata";
|
|
64
|
+
import { ReadableController, TableController, provideDbSpace } from "@atscript/moost-db";
|
|
65
|
+
import { ODataReadableController, ODataTableController, basicAuth } from "@atscript/moost-odata";
|
|
66
|
+
import { MoostHttp } from "@moostjs/event-http";
|
|
67
|
+
import { Moost } from "moost";
|
|
68
|
+
import * as sales from "../src/odata/sales.as";
|
|
69
|
+
import { model } from "../src/odata/sales.model.gen";
|
|
70
|
+
|
|
71
|
+
const space = createODataSpace({
|
|
72
|
+
baseUrl: "https://my-gateway.example.com/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
|
|
73
|
+
query: { "sap-client": "100" },
|
|
74
|
+
model,
|
|
75
|
+
types: sales,
|
|
76
|
+
init: basicAuth({ user: process.env.ODATA_USER!, password: process.env.ODATA_PASSWORD! }),
|
|
77
|
+
});
|
|
78
|
+
// The generated types carry `@db.space 'sales'`: register the space under that name.
|
|
79
|
+
provideDbSpace(space, "sales");
|
|
80
|
+
|
|
81
|
+
@TableController(sales.Order, "api/sales/OrderSet")
|
|
82
|
+
export class OrderSetController extends ODataTableController<typeof sales.Order> {}
|
|
83
|
+
|
|
84
|
+
@ReadableController(sales.Customer, "api/sales/CustomerSet")
|
|
85
|
+
export class CustomerSetController extends ODataReadableController<typeof sales.Customer> {}
|
|
86
|
+
|
|
87
|
+
await space.connect(); // the live $metadata, before app.init()
|
|
88
|
+
|
|
89
|
+
const app = new Moost();
|
|
90
|
+
// disableDuplicatePath: app.init() refuses a path registered twice instead of keeping both
|
|
91
|
+
app.adapter(new MoostHttp({ router: { disableDuplicatePath: true } })).listen(3000);
|
|
92
|
+
app.registerControllers(OrderSetController, CustomerSetController);
|
|
93
|
+
await app.init();
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`space.connect()` reads the live `$metadata` (its value-help documents included) with the space's
|
|
97
|
+
own `init`, and makes the generated classes the live declarations. Call it once before
|
|
98
|
+
`app.init()`: Moost creates the controllers there, and they read the tables' structure. A
|
|
99
|
+
`$metadata` that cannot be read rejects `connect()`, and the server does not start. What the live
|
|
100
|
+
service changed against the saved one is warned once through the space's `logger`. See
|
|
101
|
+
[Live metadata](https://odata.atscript.dev/guide/live-metadata).
|
|
102
|
+
|
|
103
|
+
Each entity set is now served with the endpoints of moost-db, the writes only where the controller
|
|
104
|
+
extends `ODataTableController`:
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
GET /api/sales/OrderSet/query?CustomerId=C1&$sort=-OrderDate&$limit=20
|
|
108
|
+
GET /api/sales/OrderSet/pages?$page=2&$size=50
|
|
109
|
+
GET /api/sales/OrderSet/one/4500000001
|
|
110
|
+
GET /api/sales/OrderSet/meta
|
|
111
|
+
POST /api/sales/OrderSet
|
|
112
|
+
PATCH /api/sales/OrderSet
|
|
113
|
+
PUT /api/sales/OrderSet
|
|
114
|
+
DELETE /api/sales/OrderSet/4500000001
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
and with [`@atscript/db-client`](https://db.atscript.dev):
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const orders = new Client("/api/sales/OrderSet");
|
|
121
|
+
await orders.pages({ filter: { CustomerId: "C1" }, controls: { $with: [{ name: "Items" }] } });
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Controllers
|
|
125
|
+
|
|
126
|
+
Declare one controller per entity set you serve, with moost-db's decorators, extending one of
|
|
127
|
+
these classes:
|
|
128
|
+
|
|
129
|
+
| Class | Endpoints | For an entity set the service |
|
|
130
|
+
| ------------------------- | ---------------------------------------------- | ------------------------------------ |
|
|
131
|
+
| `ODataReadableController` | `/query`, `/pages`, `/one`, `/meta` | lets you read (any) |
|
|
132
|
+
| `ODataTableController` | the same, and `POST`, `PUT`, `PATCH`, `DELETE` | lets you create, change or delete in |
|
|
133
|
+
|
|
134
|
+
Both are moost-db's controllers (`AsDbReadableController`, `AsDbController`) with these
|
|
135
|
+
additions:
|
|
136
|
+
|
|
137
|
+
- **`$search`** on an entity set the service cannot search is refused with `400`. moost-db itself
|
|
138
|
+
ignores such a term and answers the rows unsearched; a type whose fields carry
|
|
139
|
+
`@db.column.searchable` keeps moost-db's substring search over those fields.
|
|
140
|
+
- **Only the writes the set allows** (`ODataTableController`): `/meta` lists in `crud` the writes the
|
|
141
|
+
entity set allows (insertable, updatable, deletable), so atscript-ui shows no button that cannot
|
|
142
|
+
work. Another write is refused before any request with moost-db's `400` `NOT_SUPPORTED`, naming
|
|
143
|
+
why. A set that takes no write at all (not insertable, updatable or deletable; reached only
|
|
144
|
+
through a navigation; draft-enabled; the parameters of a parameterized view) is served the same
|
|
145
|
+
way: reads work, every write answers `400`. An `ODataReadableController` has no write routes:
|
|
146
|
+
a write answers `404`.
|
|
147
|
+
- **A set the live service no longer has**: the server still starts, and every endpoint of its
|
|
148
|
+
controller, `/meta` included, answers moost-db's `404` `NOT_FOUND`, from `prepareRequest` (an
|
|
149
|
+
override of it calls `await super.prepareRequest(ctx)` first). The start warning names it.
|
|
150
|
+
|
|
151
|
+
Failures of the service need neither class: the adapter throws atscript-db's store-failure codes,
|
|
152
|
+
which every moost-db controller answers itself (see [Errors](#errors)). A controller of moost-db's
|
|
153
|
+
own classes, or an ARBAC controller of Aooth, over an OData table answers them alike; it goes
|
|
154
|
+
without the three additions above (`$search` is answered unsearched, `crud` lists writes the set
|
|
155
|
+
refuses, a set gone live answers `500`) unless its base adds them with three exported helpers:
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
import type { FilterExpr } from "@atscript/db";
|
|
159
|
+
import type { TDbRequestContext } from "@atscript/moost-db";
|
|
160
|
+
import type { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
|
|
161
|
+
import { AsArbacDbController } from "@aooth/arbac-moost";
|
|
162
|
+
import { allowedCrud, refuseGoneEntitySet, refuseUnappliedSearch } from "@atscript/moost-odata";
|
|
163
|
+
import { Inherit } from "moost";
|
|
164
|
+
|
|
165
|
+
@Inherit()
|
|
166
|
+
export class SalesArbacTable<T extends TAtscriptAnnotatedType> extends AsArbacDbController<T> {
|
|
167
|
+
protected override async prepareRequest(ctx: TDbRequestContext) {
|
|
168
|
+
refuseGoneEntitySet(this.readable); // 404 for a set gone live
|
|
169
|
+
await super.prepareRequest(ctx);
|
|
170
|
+
}
|
|
171
|
+
protected override applySearchFallback(
|
|
172
|
+
filter: FilterExpr | undefined,
|
|
173
|
+
controls: Record<string, unknown>,
|
|
174
|
+
) {
|
|
175
|
+
const applied = super.applySearchFallback(filter, controls);
|
|
176
|
+
refuseUnappliedSearch(this.readable, filter, controls, applied); // 400 on $search
|
|
177
|
+
return applied;
|
|
178
|
+
}
|
|
179
|
+
protected override buildCrud() {
|
|
180
|
+
return allowedCrud(super.buildCrud(), this.readable); // only the writes the set allows
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
- **A set the live service no longer lets you write to**: the server starts, `/meta` drops the
|
|
186
|
+
refused writes from `crud`, and a refused write answers `400` `NOT_SUPPORTED`. The start warning
|
|
187
|
+
names it.
|
|
188
|
+
|
|
189
|
+
### Your own base class
|
|
190
|
+
|
|
191
|
+
Hooks shared by the entity sets of a service go into a class of your own between yours and ours.
|
|
192
|
+
Moost hands routes and constructor injection down only through classes marked `@Inherit()`, so
|
|
193
|
+
mark it:
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
import type { FilterExpr, TDbWriteAction } from "@atscript/db";
|
|
197
|
+
import type { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
|
|
198
|
+
import { Inherit } from "moost";
|
|
199
|
+
|
|
200
|
+
@Inherit()
|
|
201
|
+
export class SalesTable<T extends TAtscriptAnnotatedType> extends ODataTableController<T> {
|
|
202
|
+
protected override transformFilter(filter: FilterExpr): FilterExpr {
|
|
203
|
+
return { ...filter, SalesOrg: currentSalesOrg() };
|
|
204
|
+
}
|
|
205
|
+
protected override onWrite(action: TDbWriteAction, data: unknown): unknown {
|
|
206
|
+
return { ...(data as object), SalesOrg: currentSalesOrg() };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
@TableController(sales.Order, "api/sales/OrderSet")
|
|
211
|
+
export class OrderSetController extends SalesTable<typeof sales.Order> {}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Give the read-only sets an `ODataReadableController` subclass with the same read hooks.
|
|
215
|
+
|
|
216
|
+
`transformFilter` scopes the controller's own rows, not the related rows `$with` reads. Scope a
|
|
217
|
+
relation in `validateControls`, as moost-db documents it, by conjoining the scope into the
|
|
218
|
+
`$with` entry. The adapter reads relations inside the request (`$expand`), so the scope goes to
|
|
219
|
+
the service with the expansion (`Items($filter=SalesOrg eq '1000')`); on OData v2, which has no
|
|
220
|
+
filter in an expansion, such a request is refused with `400` `NOT_SUPPORTED`, never answered
|
|
221
|
+
unscoped.
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
protected override validateControls(controls: Record<string, unknown>, type: TDbControlsType) {
|
|
225
|
+
const error = super.validateControls(controls, type);
|
|
226
|
+
if (error) return error;
|
|
227
|
+
for (const entry of (controls.$with ?? []) as WithRelation[]) {
|
|
228
|
+
const scope = { SalesOrg: currentSalesOrg() };
|
|
229
|
+
entry.filter = entry.filter ? { $and: [scope, entry.filter] } : scope;
|
|
230
|
+
}
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
An authorization layer (resources, scopes and actions), custom endpoints, actions and the other
|
|
236
|
+
hooks of moost-db (`guardWrite`, `applyMetaOverlay`, …) sit on these classes as on any moost-db
|
|
237
|
+
controller. `prepareRequest` too, but the bases implement it (the gone-set check): an override
|
|
238
|
+
calls `await super.prepareRequest(ctx)` first. `returnRepresentation()` is one of them: moost-db answers an insert
|
|
239
|
+
with the stored row (db-client's `insert(row, { returning: true })`) only where the controller
|
|
240
|
+
returns `true` from it.
|
|
241
|
+
|
|
242
|
+
### Value help
|
|
243
|
+
|
|
244
|
+
atscript-ui finds the target of a foreign key or of a `@ui.valueHelp` binding through the
|
|
245
|
+
`db.http.path` of the target type. moost-db sets it when the application initializes: to the URL
|
|
246
|
+
of the controller serving the type, the application's `globalPrefix` included, provided exactly one
|
|
247
|
+
controller serves the type at a path without parameters. `/meta` carries the URL in every
|
|
248
|
+
reference to the type.
|
|
249
|
+
|
|
250
|
+
So **a value help appears when its target entity set has a controller**. A reference to an entity
|
|
251
|
+
set no controller serves gets no URL, and atscript-ui offers no value help for the field; nothing
|
|
252
|
+
warns about it.
|
|
253
|
+
|
|
254
|
+
The value-help annotations the generator writes from the service's value lists (`@ui.valueHelp`
|
|
255
|
+
with its filter, `.fill`, `.column`, `@ui.type 'select'`, `@ui.valueLabel`; see `@atscript/odata`)
|
|
256
|
+
are served in `/meta` as they are: a picker in a form narrows by the form's values and fills
|
|
257
|
+
the fields the value list returns.
|
|
258
|
+
|
|
259
|
+
#### `valueHelpControllers`
|
|
260
|
+
|
|
261
|
+
`valueHelpControllers(space, { prefix, base?, own? })` declares the controllers of the value-help
|
|
262
|
+
targets from the live types. Call it after `await space.connect()` and before `app.init()`:
|
|
263
|
+
|
|
264
|
+
```ts
|
|
265
|
+
import { ArbacResource } from "@aooth/arbac-moost";
|
|
266
|
+
import { TableController } from "@atscript/moost-db";
|
|
267
|
+
import {
|
|
268
|
+
ODataReadableController,
|
|
269
|
+
ODataTableController,
|
|
270
|
+
valueHelpControllers,
|
|
271
|
+
} from "@atscript/moost-odata";
|
|
272
|
+
import type { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
|
|
273
|
+
import { Inherit } from "moost";
|
|
274
|
+
|
|
275
|
+
@TableController(sales.Order, "api/sales/OrderSet")
|
|
276
|
+
export class OrderSetController extends ODataTableController<typeof sales.Order> {}
|
|
277
|
+
|
|
278
|
+
@Inherit() // required: Moost passes routes down only through classes marked @Inherit()
|
|
279
|
+
@ArbacResource("sales.valueHelp") // your guard (Aooth here): one grant for every value-help route
|
|
280
|
+
export class SalesValueHelp<T extends TAtscriptAnnotatedType> extends ODataReadableController<T> {}
|
|
281
|
+
|
|
282
|
+
await space.connect();
|
|
283
|
+
const own = [OrderSetController];
|
|
284
|
+
app.registerControllers(
|
|
285
|
+
...own,
|
|
286
|
+
...valueHelpControllers(space, { prefix: "api/vh", base: SalesValueHelp, own }),
|
|
287
|
+
);
|
|
288
|
+
await app.init();
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
- **Which sets.** Without `own`: every set of the service's value-help services (OData v4
|
|
292
|
+
`Common.ValueListReferences`, SAP RAP). With `own` (your controller classes): every
|
|
293
|
+
`@ui.valueHelp` target of the types they serve, in the service or in a value-help service,
|
|
294
|
+
except the sets they serve already. A value-help set only the live service has (a reference
|
|
295
|
+
the build could not read, as with a `$metadata` saved from a browser) is served too.
|
|
296
|
+
- **Routes.** `<prefix>/<service>/<EntitySet>` for a set of the service,
|
|
297
|
+
`<prefix>/<service>/<value-help service>/<EntitySet>` (the reference path without `..`) for a
|
|
298
|
+
value-help set: `/api/vh/sales/srvd_f4/sap/zdemo_country_vh/0001/ZDEMO_COUNTRY_VH`. moost-db
|
|
299
|
+
publishes each as the target's `db.http.path`; the parent's `/meta` carries it.
|
|
300
|
+
- **Read-only.** Each controller is `class extends base {}` (`base` defaults to
|
|
301
|
+
`ODataReadableController`; a class of your own needs `@Inherit()`, which the helper checks), with
|
|
302
|
+
no write routes; `$with` and relational filters answer `400` `INVALID_QUERY`.
|
|
303
|
+
- **Who may read them.** The reads are the space's, as its technical user: the service never sees
|
|
304
|
+
the end user. Your guards on `base` and your global interceptors are the only check per user;
|
|
305
|
+
without either, these routes are open to anyone who reaches the server, with every row and field
|
|
306
|
+
the technical user may read (with `own`, a set of the service is served whole). With Aooth, put
|
|
307
|
+
`@ArbacResource` on `base` (the class name, the fallback, repeats across services); ARBAC row
|
|
308
|
+
and field scopes do not apply.
|
|
309
|
+
- **One route per path.** The helper throws for a route it already made for the space (a second
|
|
310
|
+
call with the same prefix, or references that differ only by `.` / `..` segments): Moost's
|
|
311
|
+
router keeps a second handler on one path without a word and runs it when the first one throws,
|
|
312
|
+
so the twin would answer what the first one's guard refuses. Two spaces with one service name
|
|
313
|
+
and one prefix make the same routes, which the helper cannot see: a guard bypass and reads
|
|
314
|
+
across spaces. Give each space its own name, and create the adapter with
|
|
315
|
+
`new MoostHttp({ router: { disableDuplicatePath: true } })`, which makes `app.init()` refuse any
|
|
316
|
+
duplicate path.
|
|
317
|
+
- **Limits.** Only direct `@ui.valueHelp` targets of the `own` types, no `@db.rel.FK` target
|
|
318
|
+
(declare those); a target is matched by identity with the live types, so one you point at an
|
|
319
|
+
`annotate … as` copy gets no route (declare the copy's controller and pass it in `own`); pass
|
|
320
|
+
every controller of the space in `own`, or a set gets two routes and moost-db publishes none;
|
|
321
|
+
sets are fixed at start (restart for a new reference); a set with a route segment outside
|
|
322
|
+
`[A-Za-z0-9_.~-]` is skipped with a console warning.
|
|
323
|
+
|
|
324
|
+
A controller you declare by hand serves its target as well, at a path of your own; pass it in
|
|
325
|
+
`own` and the helper leaves its set alone. In `own`, a controller counts by the binding of
|
|
326
|
+
moost-db's `@TableController` / `@ReadableController`, whatever class it extends (moost-db's own
|
|
327
|
+
`AsDbReadableController` included); a value-help controller of moost-db's own
|
|
328
|
+
(`AsValueHelpController`, `AsJsonValueHelpController`) has no such binding and is not seen. A
|
|
329
|
+
target several controllers serve is moost-db's case: it warns itself, and the remedy is its
|
|
330
|
+
`canonical: true`.
|
|
331
|
+
|
|
332
|
+
#### Value-help services (OData v4, SAP RAP)
|
|
333
|
+
|
|
334
|
+
On SAP RAP v4 a value list lives in a separate value-help service (`Common.ValueListReferences`).
|
|
335
|
+
With the documents of those services given to the generator (saved by `atscript-odata fetch`, or
|
|
336
|
+
named in `valueHelps`; see `@atscript/odata`), the generated file holds an interface per
|
|
337
|
+
value-help entity set a binding targets, marked `@odata.valueHelpService`; at runtime the space
|
|
338
|
+
reads them live. Its table comes from the same space, and reads the set at the value-help
|
|
339
|
+
service's root with the space's credentials and session. `valueHelpControllers` serves each; one
|
|
340
|
+
declared by hand works as any target:
|
|
341
|
+
|
|
342
|
+
```ts
|
|
343
|
+
@ReadableController(sales.CountryVH, "api/sales/vh/CountryVH")
|
|
344
|
+
export class CountryVHController extends ODataReadableController<typeof sales.CountryVH> {}
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
A value-help set named like a set of the service itself (both have a `Country` set, say) gets an
|
|
348
|
+
interface with a suffix (`CountryType_2`) and the same `@db.table 'Country'`: declare its
|
|
349
|
+
controller with an explicit path, as above, so the two do not claim one route.
|
|
350
|
+
|
|
351
|
+
With `atscript-odata fetch` (see `@atscript/odata`) the value-help documents are saved with a manifest
|
|
352
|
+
the generator reads by itself; `valueHelps` is needed only for documents saved by hand.
|
|
353
|
+
|
|
354
|
+
## Credentials
|
|
355
|
+
|
|
356
|
+
A Moost server authenticates and authorizes its own users, with [Aooth](https://aooth.moost.org) or any
|
|
357
|
+
Moost auth. Its connection to the OData service is an integration with a technical user: the
|
|
358
|
+
service never sees the end users, and the server never passes on the incoming request's
|
|
359
|
+
`Authorization` header or cookies.
|
|
360
|
+
|
|
361
|
+
The space's `init` answers the credentials of every call; it is called once per table operation,
|
|
362
|
+
in the HTTP request it runs for. Build it from these strategies (each an `ODataAuth`):
|
|
363
|
+
|
|
364
|
+
| Strategy | Sends |
|
|
365
|
+
| -------------------------------- | ------------------------------------------------------------------------------------ |
|
|
366
|
+
| `basicAuth({ user, password })` | `Authorization: Basic …` of a technical user |
|
|
367
|
+
| `bearerAuth(token)` | `Authorization: Bearer …` of a technical token |
|
|
368
|
+
| `bearerAuth((request) => token)` | a token the function gives at every table operation (cache and refresh it there) |
|
|
369
|
+
| `staticHeaders({ … })` | fixed headers: a credential in a header of its own, such as an API key |
|
|
370
|
+
| `callTimeout(ms)` | an abort signal limiting one table operation, all its requests together (`504`) |
|
|
371
|
+
| `combineAuth(a, b, …)` | all of them merged in order; a later header replaces an earlier one of the same name |
|
|
372
|
+
| a function of your own | whatever `{ headers, signal, … }` it returns |
|
|
373
|
+
|
|
374
|
+
```ts
|
|
375
|
+
import { bearerAuth, callTimeout, combineAuth } from "@atscript/moost-odata";
|
|
376
|
+
|
|
377
|
+
// An OAuth client-credentials token that expires: `tokens` is yours, and refreshes it.
|
|
378
|
+
const init = combineAuth(
|
|
379
|
+
bearerAuth(() => tokens.current()),
|
|
380
|
+
callTimeout(15_000),
|
|
381
|
+
);
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
The function of `bearerAuth`, and a function of your own, runs in the request it is asked for:
|
|
385
|
+
`currentIncomingRequest()` gives it the request's headers and cookies (a tenant, to pick the token
|
|
386
|
+
the server obtained for it), and Wooks composables work there too. Outside an HTTP request (a job,
|
|
387
|
+
a script, the start) there is no request. An error a strategy throws reaches the caller unchanged;
|
|
388
|
+
throw an `HttpError` to choose the answer.
|
|
389
|
+
|
|
390
|
+
## Sessions
|
|
391
|
+
|
|
392
|
+
The space keeps the sessions with the service itself, one per credential the calls send: the
|
|
393
|
+
service's cookies and the CSRF token a write needs. With one technical user it is simply one
|
|
394
|
+
session; a rotating token starts a new one; two credentials never share a session or a CSRF token.
|
|
395
|
+
Calls without credentials stay stateless.
|
|
396
|
+
|
|
397
|
+
```ts
|
|
398
|
+
const space = createODataSpace({ /* … */ init, sessions: { ttl: 20 * 60_000, max: 100 } });
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
`sessions` takes `ttl` (milliseconds a session is kept after its last use, default 30 minutes)
|
|
402
|
+
and `max` (the most kept, default 1000), or `false` for none. Keep `ttl` at or below the idle
|
|
403
|
+
timeout of the service's own sessions. A dropped session is no error: the next call starts a new
|
|
404
|
+
one. Without a session (no credentials, or `sessions: false`) a write to an SAP service is refused,
|
|
405
|
+
answered `502` `STORE_FAILED`, the remedy in the server's log. See
|
|
406
|
+
[Credentials and sessions](https://odata.atscript.dev/guide/credentials-sessions).
|
|
407
|
+
|
|
408
|
+
## Errors
|
|
409
|
+
|
|
410
|
+
The adapter reports a failure of the service as one of atscript-db's store-failure codes (since
|
|
411
|
+
atscript-db 0.1.197), which moost-db answers itself, on any controller over the space, in its
|
|
412
|
+
envelope (`{ message, statusCode, code, errors }`, the code also on the one entry):
|
|
413
|
+
|
|
414
|
+
| The service | Answer | `code` |
|
|
415
|
+
| ----------------------------------------------------------------------------------------------------------------------------------- | ------ | ----------------- |
|
|
416
|
+
| `5xx` but `501`, no answer, `401` / `403` (the server's credentials), an HTML login page, a write without a session, another status | `502` | `STORE_FAILED` |
|
|
417
|
+
| timed out, or the call was aborted (`callTimeout`); `504` | `504` | `STORE_TIMEOUT` |
|
|
418
|
+
| `429` | `429` | `STORE_THROTTLED` |
|
|
419
|
+
|
|
420
|
+
- Refused credentials are always the server's fault: the server calls the service with
|
|
421
|
+
credentials it was given, and the caller can do nothing about them.
|
|
422
|
+
- A `429` sends `Retry-After` when the service named a wait (in seconds; an HTTP date becomes
|
|
423
|
+
seconds), also as `params.retryAfter` on the entry.
|
|
424
|
+
- The message is generic, rendered by `code` by the application's translator (`setTranslator` of
|
|
425
|
+
Moost) when there is one. What the service said is not in the body: its texts can name internal
|
|
426
|
+
objects, hosts and users.
|
|
427
|
+
- moost-db logs every `5xx` it answers (topic `moost-db`) with the service's error as the cause:
|
|
428
|
+
its status, code, message, the URL called, and for a write without a session the remedy.
|
|
429
|
+
|
|
430
|
+
A `400` and a `409` of the service are not among these failures, and their messages do reach the
|
|
431
|
+
caller: moost-db answers them `400` `INVALID_QUERY` and `409` `CONFLICT`. That is deliberate: they
|
|
432
|
+
are the service's answer to what the caller sent, worded for the caller, and they explain a rejected
|
|
433
|
+
filter value or a rejected write. The service's leading message is the answer's `message`;
|
|
434
|
+
`errors` lists its messages by the field their target names (the leading one only when it names a
|
|
435
|
+
field), the same on v2 and v4 and in the browser client. A service that puts internals into these
|
|
436
|
+
texts needs an interceptor of your own in front.
|
|
437
|
+
|
|
438
|
+
What moost-db answers itself, for the other errors of `@atscript/db-odata`: an operation the adapter
|
|
439
|
+
refuses (a write the entity set does not allow, which `/meta` of an `ODataTableController` leaves out
|
|
440
|
+
of `crud`; a write by filter, `$inc` / `$mul`, a version to compare, a grouped read the entity
|
|
441
|
+
set cannot answer; on OData v2 a filter or sort of a relation) `400` `NOT_SUPPORTED`, the adapter's
|
|
442
|
+
message saying why, with one entry coded `NOT_SUPPORTED` (the browser client answers a write the
|
|
443
|
+
set does not allow with the same body); a write without the version token whose entity changed
|
|
444
|
+
between the adapter's ETag read and the write on each of three attempts `503`
|
|
445
|
+
`SERIALIZATION_FAILURE`; a query the service cannot run `400`; a missing entity `404`.
|
|
446
|
+
|
|
447
|
+
## Writes
|
|
448
|
+
|
|
449
|
+
The write endpoints are moost-db's, over the writes of [`@atscript/db-odata`](https://odata.atscript.dev/guide/writes):
|
|
450
|
+
|
|
451
|
+
| Request | OData | Answer |
|
|
452
|
+
| ----------------------------------------- | ---------------------------------------- | -------------------------------------- |
|
|
453
|
+
| `POST /<Set>` with an object | `POST <Set>` | `{ insertedId }`, the service's key |
|
|
454
|
+
| `POST /<Set>` with an array | one `POST` per row, no rollback | `{ insertedCount, insertedIds }` |
|
|
455
|
+
| `PATCH /<Set>` with the key and changes | `MERGE` (v2) / `PATCH` (v4) `<Set>(key)` | `{ matchedCount, modifiedCount }` |
|
|
456
|
+
| `PUT /<Set>` with the whole entity | `PUT <Set>(key)` | `{ matchedCount, modifiedCount }` |
|
|
457
|
+
| `DELETE /<Set>/<id>`, `DELETE /<Set>?k=v` | `DELETE <Set>(key)` | `{ deletedCount }`; `404` when missing |
|
|
458
|
+
|
|
459
|
+
- **Version tokens.** A row of an entity set with optimistic concurrency carries its ETag as
|
|
460
|
+
`__etag`, and `/meta` names it `versionColumn`. A `PATCH` or `PUT` that sends it back (the row
|
|
461
|
+
as read, or `$cas: { __etag }`; db-client lifts it) is a real conditional write: the ETag goes
|
|
462
|
+
out as `If-Match`, and a change made since the read answers moost-db's `409` with `code:
|
|
463
|
+
"VERSION_MISMATCH"` and the current token in `currentVersion` (`404` when the entity is gone).
|
|
464
|
+
- **Last write wins without it.** A `PATCH` or `PUT` without the token, and every `DELETE`,
|
|
465
|
+
overwrites whatever changed since the caller read the entity, without a conflict. Where the
|
|
466
|
+
service requires `If-Match`, the adapter reads the current ETag right before the write: that
|
|
467
|
+
satisfies the service's If-Match requirement, nothing more. A change in the moment between that
|
|
468
|
+
read and the write has both repeated, three attempts in all, then `503` `SERIALIZATION_FAILURE`. An atscript-ui edit form (0.1.190
|
|
469
|
+
and later) sends the token of the row it loaded, so its save detects conflicts.
|
|
470
|
+
- **Sessions.** A write needs the session the space keeps for its credentials
|
|
471
|
+
([Sessions](#sessions)).
|
|
472
|
+
- **404 or 400.** An `ODataReadableController` has no write routes: its writes answer `404`. A
|
|
473
|
+
`ODataTableController` answers `400` `NOT_SUPPORTED` for a write the set does
|
|
474
|
+
not allow (a `DELETE` where only creates and updates are allowed; `/meta` does not offer it) and
|
|
475
|
+
for what OData cannot express ([Errors](#errors)).
|
|
476
|
+
- **Keys and values the service fills in.** A scalar the service computes (`Core.Computed`,
|
|
477
|
+
`StoreGeneratedPattern`, v2 `sap:creatable` and `sap:updatable` false) carries
|
|
478
|
+
`@db.default.store`: neither db-client, the server's validation nor an atscript-ui create form
|
|
479
|
+
demands it, it is never sent, and a computed key comes back in `insertedId` from the service's
|
|
480
|
+
answer. A GUID that is filled in only when left out (`Core.ComputedDefaultValue`, SAP CAP's
|
|
481
|
+
`cuid`) carries `@db.default.uuid`: the table layer generates one and sends it, as it sends one
|
|
482
|
+
given.
|
|
483
|
+
- **An array `POST`** goes out as one `$batch`, each row in a changeset of its own: not atomic,
|
|
484
|
+
the rows after a refused one still run. When rows are refused it answers the first refused row's
|
|
485
|
+
status and code, every refused row's entries at that row (`[1].City`) and an `INSERTED` entry
|
|
486
|
+
(`params.insertedId`) for each row created. An array `PATCH` or `PUT` stops at the first refused
|
|
487
|
+
row, and its error names no row yet.
|
|
488
|
+
- **Partial array operators** (`$insert`, `$upsert`, `$update`, `$remove`) are applied by the
|
|
489
|
+
table layer: it reads the entity and writes the whole array back, last-write-wins.
|
|
490
|
+
- **Not possible:** writes by filter, `$inc` / `$mul`, deep insert (the table layer writes nested
|
|
491
|
+
rows one by one), draft editing.
|
|
492
|
+
|
|
493
|
+
## Operations
|
|
494
|
+
|
|
495
|
+
Ask the OData plugin for the controllers module (`controllers: true`, or `{ writable: [...] }`): it
|
|
496
|
+
writes a base per entity set with operations bound to its type, each operation a moost-db db
|
|
497
|
+
action (`@DbAction` with its label and availability gate, `@InputForm` of its `<Name>Params` type,
|
|
498
|
+
`@DbActionRows`, and `@ODataOperation` with its handle), and the service's operations base, one
|
|
499
|
+
POST route per unbound operation. Extend them; never edit the generated file:
|
|
500
|
+
|
|
501
|
+
```ts
|
|
502
|
+
import { TableController } from "@atscript/moost-db";
|
|
503
|
+
import { Controller, Inherit } from "moost";
|
|
504
|
+
import * as sales from "./odata/sales.as";
|
|
505
|
+
import { OrderSetBase, SalesOperationsBase } from "./odata/sales.controllers.gen";
|
|
506
|
+
|
|
507
|
+
@TableController(sales.Order, "api/sales/OrderSet")
|
|
508
|
+
export class OrderSetController extends OrderSetBase {}
|
|
509
|
+
|
|
510
|
+
@Inherit()
|
|
511
|
+
@Controller("api/sales/ops")
|
|
512
|
+
export class SalesOperations extends SalesOperationsBase {}
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
Several rows go out as one `$batch`, by the operation's grouping, which the generated base writes
|
|
516
|
+
from the metadata (an override sets another): `isolated`, each row in a changeset of its own (the
|
|
517
|
+
default, as in Fiori Elements), or `changeSet`, all or none. A run answers moost-db's action target
|
|
518
|
+
summary (`matched`, `processed`, the gate's `skipped`, `failed` with each row's `status` and `code`)
|
|
519
|
+
with one `value` per row; every row failed is the first row's error with every row's entries at
|
|
520
|
+
`[i]`, a refused `changeSet` run its one error, nothing applied. Every generated action on rows
|
|
521
|
+
takes moost-db's `queryTarget` (atscript-ui's "all matching rows", at most 50). Where the call
|
|
522
|
+
writes, it sends the version token the row load read right before it as `If-Match`; a `412` (the
|
|
523
|
+
row changed in between) answers `409` `VERSION_MISMATCH` with the current token. A function, and
|
|
524
|
+
any call on the collection, sends `If-Match: *` on a set with a version token (SAP CAP refuses a
|
|
525
|
+
bound call without one). An operation
|
|
526
|
+
the live service no longer has answers `404`, one it changed so that the build no longer fits
|
|
527
|
+
`500`, after your guards and before any call, and both are left out of `/meta`. If you override
|
|
528
|
+
`prepareRequest`, call `await super.prepareRequest(ctx)` first. See
|
|
529
|
+
[Operations](https://odata.atscript.dev/guide/operations).
|
|
530
|
+
|
|
531
|
+
## What a client sees today
|
|
532
|
+
|
|
533
|
+
- **Writes**: see [Writes](#writes).
|
|
534
|
+
- **Aggregation**: `/query` with `$groupBy` (db-client's `aggregate()`) is one OData v4 `$apply`
|
|
535
|
+
request on an entity set that declares `Aggregation.ApplySupported`, through moost-db's own
|
|
536
|
+
aggregate path; `/meta.aggregateFns` lists the functions. See the aggregation section of
|
|
537
|
+
`@atscript/db-odata`.
|
|
538
|
+
- **`/meta`** lists more reads than an entity set can do: every query control of moost-db in
|
|
539
|
+
`crud`, `groupable` on fields of a set that cannot aggregate, and no mark for an entity set that
|
|
540
|
+
cannot count or declares a mandatory filter (reads are sent without one; a service that needs
|
|
541
|
+
it answers `400` with its message). `filterOps` lists the operators the service allows on each
|
|
542
|
+
field, none on a field it cannot filter by. A request for what the service cannot do is refused
|
|
543
|
+
with `400`. The writes in `crud` are exactly those the set allows.
|
|
544
|
+
- **`/pages` without `$sort`** is ordered by the key, and refused on an entity set whose key the
|
|
545
|
+
service cannot sort by.
|
|
546
|
+
|
|
547
|
+
## Testing
|
|
548
|
+
|
|
549
|
+
Wooks keeps one router for the whole process, and every Moost HTTP application registers its
|
|
550
|
+
routes there unless it is given a `Wooks` instance of its own. A test file that boots a second
|
|
551
|
+
application at the same paths therefore gets the handlers of the first one. Call
|
|
552
|
+
`clearGlobalWooks()` (exported by `moost`) before creating each application, or create each with
|
|
553
|
+
its own `Wooks` instance.
|
|
554
|
+
|
|
555
|
+
## License
|
|
556
|
+
|
|
557
|
+
MIT
|
|
558
|
+
|
|
559
|
+
---
|
|
560
|
+
|
|
561
|
+
SAP, SAP S/4HANA and the other SAP products named here are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. Atscript OData is not affiliated with or endorsed by SAP SE.
|