@atscript/moost-odata
Complete export reference for @atscript/moost-odata. See Moost Server, Operations, Credentials and sessions and Errors for the narrative.
pnpm add @atscript/moost-odata @atscript/db-odata @atscript/odata \
@atscript/moost-db @atscript/db @atscript/core @atscript/typescript @uniqu/core \
moost @moostjs/event-http @wooksjs/event-core @wooksjs/event-http @wooksjs/http-bodyTwo entry points: ., Node, and /client, for the browser. The package adds OData specifics to the controllers of @atscript/moost-db: base classes for the controllers you declare, the operations of the service (the marker of the generated bases and the base of the operations controller), the read-only controllers of value-help targets, and credentials strategies for the space's init. Failures of the service need nothing of it: the adapter throws Atscript DB's store-failure codes, which every moost-db controller answers itself (see Errors). You declare one controller per entity set you serve; the OData plugin's controllers option generates bases with the operations for them to extend (see Operations), and valueHelpControllers declares the controllers of the value-help targets. The sessions with the service are kept by the space of @atscript/db-odata (see ODataSessionOptions).
"An SAP service" on this page means one whose $metadata an SAP S/4HANA® or SAP Gateway® system produced (RAP services included): the engine detects it and applies the sap dialect.
Classes
ODataReadableController
class ODataReadableController<
T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType,
DataType = TAtscriptDataType<T>,
> extends AsDbReadableController<T, DataType> {
protected prepareRequest(ctx: TDbRequestContext): void | Promise<void>;
protected buildActions(): TDbActionInfo[];
protected runOperation<R = unknown>(
input: ODataOperationInput & ({ rows: readonly object[] } | { ids: readonly object[] }),
): Promise<ODataRowsAnswer<R>>;
protected runOperation<R = unknown>(input?: ODataOperationInput): Promise<ODataCallAnswer<R>>;
}moost-db's read-only controller (/query, /pages, /one, /meta) for an entity set of an OData service. On top of AsDbReadableController it:
- refuses
$searchwith400on an entity set the service cannot search (moost-db would answer every row unsearched); - answers every endpoint,
/metaincluded, with moost-db's404NOT_FOUND(notFoundError()) when the live service no longer has the entity set, fromprepareRequest. The server still starts, and the drift warning of the space names the set. A subclass that implementsprepareRequestcallsawait super.prepareRequest(ctx)first; - refuses a db action marked with
@ODataOperationwhose operation the live service no longer fits, fromprepareRequest(after the guards, before the ids are read): moost-db's404NOT_FOUNDwhen the service no longer has it, a plainError(500, logged) when it changed it so that the build's calls no longer fit (seeODataSpace.refusalOf).buildActionsleaves such actions out of/meta,$actionsandGET /meta/actions/:id, which moost-db all builds from it; - calls the operation a db action is marked with:
runOperation(see below).
Use it for every set you only read, and for the targets of value helps.
import { ReadableController } from "@atscript/moost-db";
import { ODataReadableController } from "@atscript/moost-odata";
@ReadableController(sales.Customer, "api/sales/CustomerSet")
export class CustomerSetController extends ODataReadableController<typeof sales.Customer> {}The model token resolves the space registered under the types' @db.space (provideDbSpace(space, "sales")); a table of the space (space.getTable(sales.Customer)) binds as well. A class of your own between yours and this one needs Moost's @Inherit(). Such a class is also the base of valueHelpControllers.
ODataTableController
class ODataTableController<
T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType,
DataType = TAtscriptDataType<T>,
> extends AsDbController<T, DataType> {
constructor(app: Moost, table?: AtscriptDbTable<T>);
protected buildCrud(): TCrudPermissions;
protected prepareRequest(ctx: TDbRequestContext): void | Promise<void>;
protected buildActions(): TDbActionInfo[];
protected runOperation<R = unknown>(
input: ODataOperationInput & ({ rows: readonly object[] } | { ids: readonly object[] }),
): Promise<ODataRowsAnswer<R>>;
protected runOperation<R = unknown>(input?: ODataOperationInput): Promise<ODataCallAnswer<R>>;
}moost-db's read and write controller (POST, PUT, PATCH, DELETE next to the read endpoints) for an entity set the service lets you write to. Everything ODataReadableController adds, and:
- Only the writes the set allows.
/metalists incrudonly the writes the live set allows (allowedWrites). Another write is refused with400NOT_SUPPORTEDbefore any request. - A set that takes no write at all, or one the live service no longer lets you write to, starts like any other:
/metalists no refused write incrud, and each refused write answers400NOT_SUPPORTED. The drift warning of the space names a set that lost writes.
Its writes go in the session the space keeps for the credentials it sends. See Writes and concurrency.
import { TableController } from "@atscript/moost-db";
import { ODataTableController } from "@atscript/moost-odata";
@TableController(sales.Order, "api/sales/OrderSet")
export class OrderSetController extends ODataTableController<typeof sales.Order> {}ODataOperationsController
class ODataOperationsController {
protected runOperation<R = unknown>(
input?: Pick<ODataOperationInput, "params" | "extra">,
): Promise<ODataCallAnswer<R>>;
}The base of a service's operations controller: what the generated <Service>OperationsBase extends, one POST route per unbound operation, the parameters as the JSON body. Declare a leaf over the generated base with Moost's @Controller(path) and @Inherit():
import { Controller, Inherit } from "moost";
import { SalesOperationsBase } from "../src/odata/sales.controllers.gen";
@Inherit()
@Controller("api/sales/ops")
export class SalesOperations extends SalesOperationsBase {}runOperation calls the operation the current method is marked with (@ODataOperation) on the space registered under the handle's service (provideDbSpace(space, "sales"), the types' @db.space), with the space's credentials and session (ODataSpace.callOperation). In order: an operation the live service no longer has answers moost-db's 404, one it changed a plain Error (500); params (none for a request without a body) is validated against the live <Name>Params type (moost-db's 400 envelope); the call; { value, message?, messages?, details? }. The class carries moost-db's validationErrorTransform, so the service's failures answer as on a moost-db controller (400, 409, 502, 504, 429). extra (OData v2) sends parameters the operation does not declare, untyped: set it in an override, never from the request.
Operations
ODataOperation
function ODataOperation(
operation: ODataOperationRef<any, unknown, unknown>,
options?: ODataOperationOptions,
): MethodDecorator;Marks a controller method as the route of an OData operation: operation is its typed handle of the model module's ops (ops.OrderSet.ReleaseOrder). The generated bases put it on every method, beside moost-db's @DbAction, @InputForm and @DbActionRows / @DbActionIDs. It is how runOperation() finds the operation (a method without it throws), and how the OData bases know which db actions are operations to check against the live service. Put it, with @DbAction, on a db action of your own that calls an operation (a button over an unbound one; see the recipe). An override that sets it again replaces it, a new grouping included.
runOperation
runOperation of ODataReadableController and ODataTableController calls the operation the current method is marked with, through the table's adapter (ODataAdapter.callOperation):
input | Meaning |
|---|---|
rows | An operation called on rows: the rows of @DbActionRows(), each with its key and, on a set with a version token, the __etag the row load read |
ids | The same without a row load: the ids of @DbActionIDs(), the key alone; the entity's ETag is read right before a call that writes on a set with a version token |
params | The parameters: the form of @InputForm |
extra | OData v2 only: parameters the operation does not declare, sent untyped; set in code, in an override |
The handle of a bound operation is called on the controller's entity set, the handle of an unbound one unbound. The row's __etag is the server's own read, from the row load (a caller sends ids, which carry no token); it goes as If-Match on a call that writes (a v4 action, a v2 import that is not a GET); a function, and a call on the collection, sends If-Match: * on a set with a version token. A 412 on it means the row changed between that load and the call: moost-db's 409 VERSION_MISMATCH with the entity's current token (or 404 when the entity is gone), as a stale write answers, without a retry. An id the row load does not find (an action without an availability gate) answers moost-db's 404 NOT_FOUND before any call (the gate of a gated action counts it unavailable: 409). So does a row of @DbActionIDs() whose ETag read finds no entity, its call not sent, and a row whose call the service answers 404; of several rows, that row's failed entry (status: 404, code: "NOT_FOUND"). An operation the live service no longer fits is refused by prepareRequest, before the ids are read; an override of prepareRequest that does not call super still gets it refused here, but after the row load (an availability path gone live then fails that load first). What the service answers is mapped as for every call of the table (see Errors).
On rows it answers ODataRowsAnswer, moost-db's action target summary (useDbActionTarget(): its counts, the gate's skipped rows, each failed row reported with fail(id, error), so its entry carries the status, code and message moost-db answers that error with) with one value per row that ran and the service's messages. Several rows go out as one $batch by the mark's grouping (ODataOperationOptions); with the space's batch: false one call per row, and a changeSet run is refused (400 NOT_SUPPORTED). Every row of several failed: the first row's error with every row's entries at [i]; a refused changeSet run: its one error, nothing applied (see Several rows). One row's failure is its own error. On the collection it answers { value, message?, messages?, details? }.
@atscript/moost-odata/client
The browser entry: what a page in front of a Moost server calls the operations base with. It ships no OData and no server code; it needs @atscript/db-client (an optional peer dependency), which the page has for its tables.
operationsClient
function operationsClient(
baseUrl: string,
options?: ODataOperationsClientOptions,
): ODataOperationsClient;
type ODataOperationsClientOptions = Pick<ClientOptions, "fetch" | "headers">; // of @atscript/db-client
interface ODataOperationsClient {
call<P, R>(
operation: ODataOperationRef<P, R>, // a handle of an unbound operation
...params: {} extends P ? [params?: P] : [params: P]
): Promise<ODataCallAnswer<R>>;
}baseUrl is the path of your operations controller (@Controller("api/sales/ops") over the generated operations base). call(handle, params) posts params as the JSON body to <baseUrl>/<operation> and answers what the route answers, { value, message?, messages?, details? }. The handle types it: the parameters are required when the operation has a required one, and value is its result. A non-2xx answer throws db-client's ClientError with its status and body ({ message: statusText, statusCode } for a body that is no JSON); a server that cannot be reached, or an answer that is no JSON, throws TransportError; a handle of a bound operation throws Error (it is a db action of its table's controller). See From a Moost page.
import { operationsClient } from "@atscript/moost-odata/client";
import { ops } from "./odata/sales.model.gen";
const salesOps = operationsClient("/api/sales/ops", {
headers: () => ({ Authorization: token() }),
});
const { value } = await salesOps.call(ops.GetPrice, { Material: "M-100" });Functions: controllers of another base
What the two base classes add, for a moost-db controller that extends another base over an OData table: an ARBAC controller of Aooth, or moost-db's own classes. Each does nothing for a table of another adapter. See Moost DB's own classes and Aooth's ARBAC controllers for the whole base class.
refuseGoneEntitySet
function refuseGoneEntitySet(readable: AtscriptDbReadable<any>): void;Throws moost-db's 404 NOT_FOUND (notFoundError()) when the live service no longer has the table's entity set. Call it first in prepareRequest, which moost-db runs on every endpoint, /meta included; without it such a table answers 500.
protected override async prepareRequest(ctx: TDbRequestContext) {
refuseGoneEntitySet(this.readable);
await super.prepareRequest(ctx);
}refuseUnappliedSearch
function refuseUnappliedSearch(
readable: AtscriptDbReadable<any>,
filter: FilterExpr | undefined,
controls: Record<string, unknown>,
applied: FilterExpr | undefined,
): void;Throws 400 INVALID_QUERY on $search when moost-db's applySearchFallback returned the filter unapplied (applied === filter) on a table that cannot search; moost-db would answer every row unsearched.
protected override applySearchFallback(filter: FilterExpr | undefined, controls: Record<string, unknown>) {
const applied = super.applySearchFallback(filter, controls);
refuseUnappliedSearch(this.readable, filter, controls, applied);
return applied;
}allowedCrud
function allowedCrud(crud: TCrudPermissions, readable: AtscriptDbReadable<any>): TCrudPermissions;crud without the writes the entity set does not allow (insert; update and replace; remove), by the adapter's allowedWrites. Return it from buildCrud of a write controller, so /meta offers only what the set takes.
protected override buildCrud() {
return allowedCrud(super.buildCrud(), this.readable);
}Functions: value help
valueHelpControllers
function valueHelpControllers(space: ODataSpace, options: ValueHelpControllerOptions): Function[];The read-only controllers of the value-help targets of a live space, made from its live types: call it after await space.connect() and before app.init(), and register what it returns. Without own, every set of the service's value-help services; with own, every @ui.valueHelp target of the types those controllers serve (in the service or in a value-help service), except the sets they serve. Each is class extends base {}, named <EntitySet>ValueHelpController, bound with moost-db's @ReadableController at <prefix>/<service>/<EntitySet> or <prefix>/<service>/<value-help service>/<EntitySet>. It refuses $with and relational filters with 400 INVALID_QUERY and has no write routes. Its reads are the space's, as the technical user: guard the routes through base or a global interceptor. A set with a route segment outside [A-Za-z0-9_.~-] gets no route, with a console warning. See Value-help controllers.
Throws before the space is connected, for a space over an engine at hand (createODataSpace({ service })), for a base that is no ODataReadableController or misses @Inherit() between the two, and for a route made twice for the space (a second call with the same prefix and a base of another name, or references that differ only by . / .. segments): Moost's router would keep both handlers and answer with the second what the first one's guard refuses. A call made again with a base of the same name makes its routes again, as a dev server's reload does (@moostjs/vite runs the entry again over the space it kept). Bases are told apart by name (a class without a name only as itself), so give the classes a factory makes distinct names; disableDuplicatePath is the guard that refuses duplicates at app.init(). Two spaces with one service name and one prefix make the same routes too; create the adapter with new MoostHttp({ router: { disableDuplicatePath: true } }) so that app.init() refuses any duplicate path.
import { valueHelpControllers } from "@atscript/moost-odata";
await space.connect();
const own = [OrderSetController];
app.registerControllers(
...own,
...valueHelpControllers(space, { prefix: "api/vh", base: SalesValueHelp, own }),
);
await app.init();Functions: credentials
A Moost server authenticates and authorizes its own users (with Aooth, or any Moost auth). Its connection to the OData service is an integration with credentials the server is given, a technical user: the service never sees the end users, and the server never passes on the incoming request's Authorization header or cookies.
Each strategy is an ODataAuth: an init function for createODataSpace, called once per table operation, in the HTTP request it runs for, and by space.connect() for the $metadata read. See Credentials and sessions.
basicAuth
function basicAuth(options: { user: string; password: string }): ODataAuth;HTTP Basic authentication of a technical user. Throws for an empty user name and for one that contains :.
const space = createODataSpace({
// … baseUrl, query, model, types
init: basicAuth({ user: process.env.ODATA_USER!, password: process.env.ODATA_PASSWORD! }),
});bearerAuth
function bearerAuth(
token: string | ((request: IncomingRequest) => string | Promise<string>),
): ODataAuth;Bearer authentication of a technical user: a token, or a function asked for one at every table operation. The function caches and refreshes a token that expires (an OAuth client-credentials token, for example); it runs in the request it is asked for and receives it. Throws when there is no token to send.
const auth = bearerAuth(() => tokens.current()); // tokens: your client-credentials cachestaticHeaders
function staticHeaders(headers: Record<string, string>): ODataAuth;Headers sent with every call: a credential the server was given in a header of its own, such as an API key (staticHeaders({ "x-api-key": key })).
callTimeout
function callTimeout(ms: number): ODataAuth;Limits every table operation to ms milliseconds, all its OData requests together. A call that takes longer fails as a timeout, answered 504 STORE_TIMEOUT. Throws for a limit that is not a positive number.
combineAuth
function combineAuth(...strategies: ODataAuth[]): ODataAuth;One strategy out of several, each asked for the current request and the answers merged in the order given: a later header replaces an earlier one of the same name (in any case), a later session replaces an earlier one, read options are merged, and the call aborts when any signal fires.
const space = createODataSpace({
// … baseUrl, query, model, types
init: combineAuth(basicAuth({ user, password }), callTimeout(15_000)),
});currentIncomingRequest
function currentIncomingRequest(): IncomingRequest;The HTTP request of the current event, read with Wooks' useHeaders and useCookies on the event context Wooks keeps in AsyncLocalStorage, so overlapping requests never see each other's. Read it in a credentials function of your own, for example to pick the token the server obtained for a tenant. Outside an HTTP event (a job, a script, application start) headers is empty and event is undefined.
Constants
The session constants DEFAULT_SESSION_TTL and DEFAULT_MAX_SESSIONS are exported by @atscript/db-odata.
Types
ODataOperationOptions
interface ODataOperationOptions {
/** An operation on rows: how several rows are sent. */
grouping?: ODataOperationGrouping; // "isolated" | "changeSet"
}The options of ODataOperation. The generated bases write the build's grouping (the InvocationGrouping of the UI.DataFieldForAction naming the operation, else isolated, Fiori's default) on every operation called on rows: several rows go out as one $batch, each row in a changeset of its own (isolated: the rows that ran stay applied when others fail) or all in one (changeSet: applied all or none). An override in your subclass sets another; a live change of it is neither refused nor followed. See Several rows.
ODataOperationInput
interface ODataOperationInput {
rows?: readonly object[];
ids?: readonly object[];
params?: object;
extra?: ODataExtraParams;
}What runOperation of the set bases takes; the operations base takes params and extra. See the table there.
ValueHelpControllerOptions
interface ValueHelpControllerOptions {
/** The route prefix of every value-help route: `api/vh`. */
prefix: string;
/** The class every controller extends. Default `ODataReadableController`. */
base?: typeof ODataReadableController<any>;
/** The application's own controller classes. */
own?: readonly Function[];
}The options of valueHelpControllers. base is ODataReadableController or a subclass of it, each class between them marked @Inherit(): where the guards (@Authenticate, @ArbacResource, interceptors) and hooks of every value-help route go. own lists every controller of the space you register: the helper then serves only the value-help targets of their types, and no set one of them serves.
ODataAuth
type ODataAuth = () => ODataCallInit | undefined | Promise<ODataCallInit | undefined>;A credentials strategy: what the init option of createODataSpace takes, called once per table operation, in the HTTP request it is made for. It returns the credentials the server was given for the service, and may add a time limit (callTimeout). A function of your own is one too; currentIncomingRequest() gives it the request. An error it throws reaches the caller unchanged: throw an HttpError to choose the answer.
IncomingRequest
interface IncomingRequest {
/** The request headers, names in lower case. */
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
/** The event context of the request, for composables that take one. */
readonly event: EventContext | undefined;
/** One header as a single string; name in any case. */
header(name: string): string | undefined;
/** One cookie, as Wooks' useCookies reads it: name in any case, split at "; ", "" → undefined. */
cookie(name: string): string | undefined;
}What currentIncomingRequest answers, and what a bearerAuth function receives.