@atscript/odata
Complete export reference for the main entry of @atscript/odata. See the Guide for the narrative: Generating models, the browser client and the Moost server build on what is listed here.
pnpm add @atscript/odata @atscript/core @atscript/typescript @atscript/db @atscript/ui @uniqu/core
pnpm add -D unplugin-atscript| Entry point | Runs in | Holds |
|---|---|---|
@atscript/odata | browser, Node | This page: the live source, operations, the service engine, $metadata parser, runtime type builder, dialects, errors, and the building blocks below them |
@atscript/odata/plugin | Node | The Atscript plugin and fetchODataMetadata: see @atscript/odata/plugin and CLI |
atscript-odata (bin) | Node | atscript-odata fetch: see CLI |
Most applications use nothing of this page directly. They hand the generated model and the generated module (import * as sales from "./odata/sales.as") to a host, @atscript/odata-client in the browser or @atscript/db-odata on a server, and the host connects a live source over them: typed at build time, live at runtime (see Live metadata). createODataService and connectODataService are the low-level engines, for tests, scripts and tools. The building blocks are for writing a host of your own.
Values on the Atscript side are what the generated types declare: a decimal as a string, a date-only value as YYYY-MM-DD, a v2 Edm.DateTime as epoch milliseconds, an Edm.DateTimeOffset as an ISO string. Property paths use . between segments (Address.City).
"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.
Live metadata
What both hosts run on: the live $metadata of the service, compared with the one the models were generated from. See Live metadata for the narrative.
createODataSource
function createODataSource(options: ODataSourceOptions): ODataSource;Creates the live source of a service. No request is made until connect(). connect() reads the live $metadata and every value-help document the build recorded, in the language the models were saved in, then:
- fast path: every document has the digest
model.buildrecords, and every document the build could not read still cannot be read. Nothing is parsed or rebuilt: the engine runs on the saved model, the generated classes stay as compiled. - slow path otherwise: the live documents are parsed and planned as at build time, the generated classes are rebuilt in place, and the changes the app's own
annotateblocks made are written on them again.
The drift report is opt-in: with onDrift, the slow path also computes what the live metadata changed against the saved one, hands it to onDrift and keeps it as connection.drift. Without onDrift no drift is computed and nothing is logged. The Moost server's space passes it; the browser client does not, as it runs on whatever the live service has.
Without model and types the types are built from the live documents (runtime-only mode): no fast path, no drift.
A generated module holds one live state per process: the first connection over it binds it. Another source over the same module reuses that state when it reads the same documents, and throws when it reads other ones. The hosts create the source for you (createODataClientFactory, createODataSpace); call it yourself in a host of your own.
import { createODataSource } from "@atscript/odata";
import * as sales from "./odata/sales.as";
import { model } from "./odata/sales.model.gen";
const source = createODataSource({
baseUrl: "/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
query: { "sap-client": "100" },
model,
types: sales,
});
const { service, fast } = await source.connect();
// sales.Order is the live declaration from here onThrows Error when types comes without a model that has a build record (model.build; regenerate the models), and when no name can be told.
ODataSourceOptions
interface ODataSourceOptions extends ODataConnectOptions {
/** @db.space of the types. Default: model.build.service; required without model. */
name?: string;
/** The model of the generated model module. */
model?: ServiceModel;
/** The generated .as module, whole (import * as sales), after the app's annotate modules. */
types?: Record<string, unknown>;
/** The app's `annotate X as Y` copies that annotate properties of their own. */
copies?: readonly TAtscriptAnnotatedType[];
/** Without model: limits the types to these entity sets and what they reference. */
entitySets?: string[];
/** Asks for the drift report of the slow path; without it no drift is computed. */
onDrift?: (drift: ODataDrift, message: string) => void;
/** Holds the live service to the build's operations: verdicts and refusals on the slow path. */
verdicts?: boolean;
}Every option of ODataConnectOptions (baseUrl, query, headers, session, language, …) plus the fields above. language defaults to the one the models were saved in (model.build.language).
| Option | Meaning |
|---|---|
name | The service's name: @db.space of its types, its URL segment in the browser client. Default: the name the models were generated with. |
model | The model export of the generated *.model.gen.ts. Its build record is what the live documents are compared with. |
types | The generated .as module, whole. Import the app's own annotate modules before connecting: their changes are carried over to the live classes. |
copies | Every annotate X as Y copy of a generated declaration that annotates properties. A copy without property entries follows X by itself. See Your annotate blocks. |
onDrift | Asks for the drift report: called once on the slow path, unless the drift holds nothing. message is driftMessage of the drift. Without it no drift is computed and nothing is logged. |
verdicts | On the slow path over a generated module, gives every operation the build selected a verdict against the live metadata: those gone or incompatible become connection.refusals, which runOperation refuses, and the drift gets operations. The Moost server's space (createODataSpace of @atscript/db-odata) always sets it; the browser client never does. The fast path compares nothing. |
ODataSource
interface ODataSource {
readonly name: string;
/** The saved model (options.model). */
readonly model?: ServiceModel;
/** The language the metadata is read in: options.language, else the saved model's. */
readonly language?: string;
/** The connection, once one succeeded. */
readonly connection: ODataConnection | undefined;
connect(init?: ODataSendInit): Promise<ODataConnection>;
}connect(init) reads with the session, signal and headers of init. One read serves every caller; a failed one is not kept, so the next call reads again. Once it succeeded it resolves with the same connection ever after. Rejects with what reading $metadata throws (ODataError, the parser's Error for an answer that is no $metadata document), and with Error when the generated module is already connected to other documents.
ODataConnection
interface ODataConnection {
readonly name: string;
/** The engine over the live model (on the fast path the saved one, which is the same). */
readonly service: ODataService;
/** The declarations by name: the live classes of `types`, or the types built at runtime. */
readonly types: BuiltTypes;
/** What the types were built from, when they were built (plan.skipped among it). */
readonly plan?: ServicePlan;
/** The live documents are the saved ones: nothing was parsed or rebuilt. */
readonly fast: boolean;
/** What the live metadata changed against the saved one: slow path, with onDrift only. */
readonly drift?: ODataDrift;
/** The build's operations the live service no longer fits, by <Name>Params: slow path, with verdicts only. */
readonly refusals?: Readonly<Record<string, ODataOperationVerdict>>;
}A generated declaration the live service no longer has is not among types; a declaration only the live documents have is, an operation type (<Name>Params) included. drift is there on the slow path over a generated module when the source was given onDrift; refusals (an empty object when every operation fits) when it was given verdicts.
ODataDrift
interface ODataDrift {
/** Entity sets (Set, or <value-help service>/Set) added and removed. */
entitySets: { added: string[]; removed: string[] };
/** Entity sets that allow fewer writes than they did: "OrderSet: insert, delete". */
writes: string[];
/** Properties (Interface.property) added and removed, of interfaces in both. */
properties: { added: string[]; removed: string[] };
/** Changes of a property's type, optionality or non-text annotations. */
changed: string[];
/** The app's annotate changes that could not be carried over: their path and keys. */
dropped: string[];
/** The build's operations against the live ones: with verdicts only. */
operations?: { added: string[]; removed: string[]; incompatible: string[] };
}What the live metadata changed against the saved one, as far as the generated types see it, for example Order.Name: expect.maxLength 40 → 60 in changed. Texts (labels, descriptions, headings) are not drift: they are simply live. Writes a set newly allows are not listed. Operation types are not in properties and changed: with verdicts, operations lists the operations only the live service offers, those gone, and those incompatible with the reason (ReleaseOrder: parameter Note Edm.String → Edm.Int32); see operationsDrift.
driftOf
function driftOf(
saved: { plan: ServicePlan; model: ServiceModel },
live: { plan: ServicePlan; model: ServiceModel },
dropped?: string[],
): ODataDrift;The drift between two plans planned with the same options, and their models (for the writes each entity set allows). A source given onDrift computes it on the slow path; use it to compare two saved documents yourself.
driftMessage
function driftMessage(service: string, drift: ODataDrift, lines?: number): string;The drift as one message for a log: a summary line and at most lines details (default 12). What the Moost server's space warns with.
isNoDrift
function isNoDrift(drift: ODataDrift): boolean;Whether the drift holds nothing. A source does not call onDrift for such a drift (a slow path for changed labels only, for example).
metadataDigest
function metadataDigest(text: string): string;The digest of a $metadata or value-help document: what the generator records in model.build and the source compares a live document with. A byte order mark, line ends and whitespace between tags do not count, so a copy saved from a browser or checked out with other line ends has the digest of the document the service sends. Any other difference gives another digest. Not a security hash.
Operations
Function imports, functions and actions: the generated operation types (<Name>Params, see Generating models), the typed handles of the model module (ops), and the runner both hosts call. Hosts call runOperation for you; call it yourself in a host or a script of your own.
runOperation
function runOperation(
connection: ODataOperationConnection,
input: ODataRunInput,
init?: ODataSendInit,
): Promise<ODataCallAnswer>;Runs an operation of the connection's selection. In order:
- With
connection.refusals(a source created withverdicts), an operation the live service no longer fits is refused:OPERATION_GONEfor one it no longer has; a plainError(the server's build no longer fits; Moost DB answers500) for one it changed incompatibly. - The operation is found among those the connection selects, by its handle or its name and the binding (the entity set, rows or none):
UNKNOWN_OPERATIONwhen none is (a draft lifecycle operation included),INVALID_BINDINGwhen the entity set or the rows do not fit it. paramsis validated against its live<Name>Paramstype: the validator'sValidatorError(@atscript/typescript/utils), with the type'sannotatechanges in effect.extrais refused on OData v4 (UNKNOWN_PARAMETER), and for a name the operation declares (DECLARED_PARAMETER).- An operation called on rows: each row's key fills its call, and a row that is not there (
nullorundefined, the gap a row load leaves for an id it did not find) is refused withINVALID_KEY, never called without its key. A call that writes (a v4 action, a v2 import that is not aGET) sends the row's__etagasIf-Match, and on an entity set with a version token a row without one gets the entity's current ETag, read first (the whole entity;*where the set cannot be read from the root, or the entity comes without an ETag). Every other call bound to an entity set with a version token (a function on a row, any operation on the collection) sendsIf-Match: *(the entity exists; SAP CAP refuses a bound call withoutIf-Match,428), never a row's__etag, nothing read first; a set without one gets none. A412on the row's own__etag(a call that writes:sendsRowToken) is the caller's version mismatch (the Moost server answers409VERSION_MISMATCH); a412on*or on an ETag the runner read is not; on one row, one on an ETag the runner read has it read again and the call sent again, three attempts in all (retryWhileChanged), then thrown, whichdbFailureOfanswersSERIALIZATION_FAILURE. - One row, the collection or none: one call, its failure thrown. The answer's
valueis what the operation returned (an array of one for a call on rows; a returned entity carries its ETag as__etag), with the service's messages. - Several rows: one
$batch(several past the transport'smaxParts) by the grouping,input.grouping, else the operation's (OperationModel.grouping), elseisolated:isolated: each row's call in a changeset of its own (OData v4 addsPrefer: odata.continue-on-error; parts the service leaves unanswered go out again). Every row that ran has its value invalue; a failed one isnullthere and infailedwith its index and what the engine threw for it, as that call alone would have thrown it.detailsholds the messages of the rows that ran, each with its row's key asid.changeSet: every call in one changeset. Applied, it answers as above; refused, it throws the changeset's oneODataError(changeset: { size }) with every call's messages, those that name a row marked with its index (row: by the Content-ID of its request on v4, by a target that is the row's key path on v2), whichdbFailureOfreports at that row ([1]).- An operation that does not write (a function) goes out a part per row, whatever the grouping. The ETags the runner reads itself go first, in a
$batchof their own (one by one for anisolatedrun on a service that turns out to have no$batchendpoint); each row's call is sent with the ETag read, not read again, also after a412. UnderchangeSeta row whose ETag cannot be read refuses the run before its changeset is sent, as a refused changeset (changeset: { size }), that row's error at the row; nothing is applied. A$batchthat failed as a whole (no answer, refused) throws its error; underchangeSetone the service has no endpoint for, the ETag reads' included, refuses the run withCHANGESET_WITHOUT_BATCH: the run never goes out row by row. - Without
$batch(input.batch: false, a service created withbatch: false, a model whose container saysCapabilities.BatchSupportedfalse, or a service that answered a$batch404,405or501in the last ten minutes) anisolatedrun goes one call after the other, on past a failed row, answered alike; achangeSetrun is refused before any call withCHANGESET_WITHOUT_BATCH.
Every refusal comes before any request; it is an ODataWriteError but for the validator's. What the call throws is the engine's (ODataError for the service's answer).
import { createODataSource, runOperation } from "@atscript/odata";
import * as sales from "./odata/sales.as";
import { model, ops } from "./odata/sales.model.gen";
const connection = await createODataSource({ baseUrl, model, types: sales }).connect();
const { value: price } = await runOperation(connection, {
operation: "GetPrice",
params: { Material: "M-1" },
});
await runOperation(connection, {
operation: ops.OrderSet.ReleaseOrder, // a handle of the model module, or a name and `entitySet`
rows: [{ OrderId: "1", __etag: order.__etag }],
params: { Note: "ok" },
extra: { Context: "SD" }, // OData v2 only: sent untyped
});incompatibleOperationError
function incompatibleOperationError(verdict: ODataOperationVerdict): Error;The plain Error of an operation the live service changed so that the build's calls no longer fit (verdict incompatible): "The operation … changed on the data service (…); the build no longer fits it: rebuild it", a fault of the server's build that Moost DB answers 500 and logs. What runOperation throws for it, and what the OData bases of @atscript/moost-odata throw. Throw it from a host of your own that checks the verdict itself.
ODataRunInput
interface ODataRunInput {
/** A handle of the model module's ops, or the name (a handle's operation, or the local name). */
operation: string | ODataOperationRef<any, unknown, unknown>;
/** With a name, a bound operation's entity set (a handle names its own). */
entitySet?: string;
/** An operation called on rows: the rows, each with its key and __etag. */
rows?: readonly Record<string, unknown>[];
/** The parameters, validated against the live operation type. */
params?: Record<string, unknown>;
/** OData v2 only: parameters the operation does not declare, sent untyped. */
extra?: ODataExtraParams;
/** Several rows: how they go out; default the operation's grouping, else "isolated". */
grouping?: ODataOperationGrouping;
/** false: several rows go out one call after the other, never as one $batch. */
batch?: false;
}A bound operation is called on rows (rows) or on its entity set (table, no rows) as the selection gives its level; an unbound one takes neither. The operation is matched by name and binding; a handle's paramsType only tells apart what still fits more than one. Give extra from code only, never from a request body: it is sent unchecked.
The hosts take it typed (callOperation of the space and the adapter of @atscript/db-odata) or by name (their callOperationByName):
type ODataTypedRunInput<P, R, K> = Omit<
ODataRunInput,
"operation" | "entitySet" | "params" | "rows"
> & {
operation: ODataOperationRef<P, R, K>;
} & ODataParamsOf<P> & // params: required when P has a required property
ODataRowsOf<K, "rows", readonly K[]>; // rows: required for an operation on rows, refused for any other
type ODataNamedRunInput = Omit<ODataRunInput, "operation"> & { operation: string };
type ODataRunValue<R, K> = [K] extends [never] ? R : unknown extends K ? unknown : (R | null)[]; // the answer's value: one per row on rowsP, R and K are inferred from the handle alone, so a parameter or a row of the wrong type is an error on that property (see ODataTypedCallInput).
ODataOperationConnection
interface ODataOperationConnection {
readonly service: ODataService;
/** The declarations by name, the operation types among them. */
readonly types: BuiltTypes;
/** What the types were built from; without it the engine's model is planned once. */
readonly plan?: ServicePlan;
/** The build's operations the live service no longer fits, by <Name>Params. */
readonly refusals?: Readonly<Record<string, ODataOperationVerdict>>;
}What runOperation runs on: an ODataConnection is one. On the fast path a connection has no plan: the selection is taken from the model module's model and its build record once.
ODataOperationGrouping
type ODataOperationGrouping = "isolated" | "changeSet";How an operation called on several rows sends them in their one $batch: each row's call in a changeset of its own, each row with its own outcome (isolated, Fiori Elements' default), or all in one changeset, which the service applies all or none (changeSet). The parser reads it from the InvocationGrouping of the UI.DataFieldForAction naming the operation (OperationModel.grouping). See Several rows.
ODataCallAnswer
interface ODataCallAnswer<R = unknown> {
/** What the operation returned; on rows one value per row, null for a failed one. */
value: R;
/** The text of the leading message. */
message?: string;
/** The texts of the messages, each once. */
messages?: string[];
/** The messages as the service sent them (sap-message / sap-messages); on several rows each with its row's key. */
details?: ODataRowMessage[];
/** Several rows, isolated: the rows whose call failed, with what the engine threw for each. */
failed?: { index: number; error: unknown }[];
}
type ODataRowMessage = ODataMessage & { id?: Record<string, unknown> };What runOperation answers. Without messages from the service, only value. failed is there only when a row of several failed; the hosts turn it into ODataRowsAnswer.
ODataRowsAnswer
interface ODataRowsAnswer<R = unknown> extends TDbActionTargetSummary {
// matched, processed, skipped, failed: Moost DB's
/** One per row that ran, in request order; null for a failed one. */
value: (R | null)[];
message?: string;
messages?: string[];
details?: ODataRowMessage[];
}What a db action of an operation on rows answers, on both hosts: the generated bases of a Moost server (through Moost DB's action target, useDbActionTarget()) and the browser client's action(). It is Moost DB's action target summary (TDbActionTargetSummary of @atscript/db), which Atscript UI recognises: matched the rows asked for, processed those that ran, skipped those the availability gate left out (none in the browser), failed those whose call failed. Each failed entry carries the status a call on the row alone is answered with and that answer's code (INVALID_QUERY, CONFLICT, VERSION_MISMATCH, …), with the error's message as reason; failed has Moost DB's entry type, a union that entry.status !== undefined narrows to that member. See Several rows for its outcomes.
ODataOperationRef
interface ODataOperationRef<P = Record<string, unknown>, R = unknown, K = never> {
readonly service: string;
/** The name the engine calls it by. */
readonly operation: string;
/** A bound operation: the entity set it is called on. */
readonly entitySet?: string;
/** Its form: the name of its <Name>Params declaration in the generated .as module. */
readonly paramsType: string;
/** Phantom: the types of a typed call. Never set. */
readonly types?: { params: P; result: R; row: K };
}A typed handle, as the model module's ops holds them: P is the <Name>Params type, R the result (an entity or complex interface, R[] for a collection, a primitive, void when it returns nothing), K the row of an operation called on rows (Pick<Order, "OrderId" | "__etag">). paramsType names its form in the generated .as module: a host finds the live form type there (types[ref.paramsType]). The operation's facts (availability, grouping) are in the service model (OperationModel.available, .grouping).
ODataCallInput
interface ODataCallInput<P = Record<string, unknown>, K = never> {
params?: P;
/** OData v2 only: parameters the operation does not declare, sent untyped. */
extra?: ODataExtraParams;
/** An operation called on rows: the row. */
row?: K;
}What a call of an operation takes: the loose shape, which callByName of the browser client factory takes (see @atscript/odata-client).
ODataTypedCallInput
type ODataTypedCallInput<P, K> = Pick<ODataCallInput, "extra"> &
ODataParamsOf<P> & // params: required when P has a required property
ODataRowsOf<K, "row", K>; // row: required when K is a row, refused when K is neverWhat a typed call of the handle ODataOperationRef<P, R, K> takes: call(handle, input) of the browser client factory. ODataParamsOf<P> is { params: P } when P has a required property, else { params?: P }; ODataRowsOf<K, F, V> makes F required (typed V) for an operation called on rows, refuses it (K is never) for any other, and leaves it optional for a handle whose row type is not known (unknown).
ODataExtraParams
type ODataExtraParams = Record<string, string | number | boolean | null>;Parameters an OData v2 function import does not declare: a number or a boolean is sent bare, a string quoted (' doubled), null as null.
selectOperations
function selectOperations(model: ServiceModel, build?: OperationSelection): PlanOperation[];
type OperationSelection = Partial<Pick<ServiceModelBuild, "service" | "entitySets" | "operations">>;The operations a model offers, by the one rule the generator, the model module and both hosts apply: every operation but the draft lifecycle ones, those operations.exclude names, those the service marks never available (Core.OperationAvailable false), those bound to a type no selected entity set serves, and those whose types fall outside the closure of entitySets or that the engine cannot call (a structured v2 parameter, a structured v4 function parameter, overloads bound alike), which the plan lists as skipped. The complex and enumeration types the selected operations use join the selection; a returned entity set does not. Default build: the model's build record, so a model module's model selects what was generated.
Each PlanOperation names its <Name>Params type, the name the engine calls it by, its binding, its level (rows on an entity: v4 bound to an entity, v2 when its parameters cover the key; table otherwise) and the entity sets it is called on.
operationsOf
function operationsOf(connection: ODataOperationConnection): PlanOperation[];The operations a connection runs, as runOperation finds them: its plan's (on the slow path the live selection, live-only operations included), or on the fast path, without a plan, the selection of its engine's model by the build record, planned once per model. The browser client lists its actions from it.
operationOf
function operationOf(model: ServiceModel, op: PlanOperation): OperationModel | undefined;The operation of the service model a selected operation is, by its name and binding: where its facts are (the HTTP method, the parameters, available, grouping). See operationWrites.
operationWrites
function operationWrites(operation: OperationModel | undefined): boolean;Whether a call of an operation writes: its method is no GET (a v4 action, a v2 import that is not a GET). Only such a call sends a row's __etag as If-Match, as Fiori Elements does; every other call bound to a set with a version token (a function, an operation on the collection) sends If-Match: * instead (runOperation), so it needs no token. false for undefined. The runner, the generated bases and the browser client decide by it.
sendsRowToken
function sendsRowToken(connection: ODataOperationConnection, input: ODataRunInput): boolean;Whether runOperation sends the rows' own __etag as If-Match for input: the operation it finds writes (operationWrites). A 412 on such a call, on a row that carries its token, is the caller's version mismatch; a 412 on any other call (If-Match: *, or an ETag the runner read) is not. false for an operation the connection does not find. Both hosts answer a stale token by it.
runParameters
function runParameters(connection: ODataOperationConnection, input: ODataRunInput): string[];The names of the parameters of the operation runOperation finds for input (a v4 binding parameter is none; a v2 key parameter is one), for the parameters of an ODataMessageContext: both hosts map the messages of a failed run with them, so a message whose target names a parameter is reported at that parameter, the field of the operation's input form, on a bound operation as on an unbound one. Empty for an operation the connection does not find.
demandsOtherFilter
function demandsOtherFilter(
model: ServiceModel,
entitySet: string,
key: readonly string[],
): boolean;Whether reads of an entity set must filter on a property outside its key (sap:required-in-filter, Capabilities.FilterRestrictions/RequiredProperties): a read of rows by their key alone would be refused. Such a set's operations read no rows first (a Moost server's generated actions take @DbActionIDs(), the browser reads no tokens); the runner reads each entity's ETag where the call needs one.
operationVerdicts
function operationVerdicts(
saved: PlannedModel,
live: PlannedModel,
): Record<string, ODataOperationVerdict>;
interface PlannedModel {
plan: ServicePlan;
model: ServiceModel;
}A verdict for every operation the build selected (saved.plan.operations), by its <Name>Params type, against the live metadata; both plans planned with the same options. A source created with verdicts computes them on the slow path and keeps the refused ones as connection.refusals.
| Verdict | When |
|---|---|
compatible | A call the build makes still fits: the same binding, every saved parameter with its Edm type (a v2 calendar date included) and collection-ness, no parameter made required, no new required one; for an operation on rows the same availability path to a Boolean; its <Name>Params name still its own. Facets, labels, the result and the v2 method may change; the grouping is no part of the verdict (the Moost server runs on the build's, the browser follows the live metadata). |
gone | The live service no longer has it, or binds it to something else (unbound, another type, entity versus collection). |
incompatible | A parameter removed, retyped or made required; a new required parameter; an availability path changed, gone or no longer a Boolean; overloads bound alike; the live plan gives its <Name>Params name to another declaration (its generated class would be rebuilt as that one's form); or the live selection no longer offers it. |
ODataOperationVerdict
interface ODataOperationVerdict {
verdict: "compatible" | "gone" | "incompatible";
/** The operation as the build selected it. */
operation: PlanOperation;
/** ReleaseOrder; on v4 a bound one with its binding: Ns.Release(Ns.Order). */
label: string;
/** Why it is gone or incompatible: "parameter Note Edm.String → Edm.Int32". */
reason?: string;
}operationsDrift
function operationsDrift(
verdicts: Record<string, ODataOperationVerdict>,
saved: ServicePlan,
live: ServicePlan,
): { added: string[]; removed: string[]; incompatible: string[] };The operations part of ODataDrift: the labels of operations only the live plan selects, of those gone, and label: reason of those incompatible.
Service engine
createODataService
function createODataService(options: ODataServiceOptions): ODataService;Creates the engine of one OData service from a model that is already at hand: the model export of a generated *.model.gen.ts module, or the result of parseMetadata. No request is made. The hosts create it over the live model themselves; call it for tests, scripts and tools that run on a saved model.
import { createODataService } from "@atscript/odata";
import { model } from "./odata/sales.model.gen";
const service = createODataService({
model,
baseUrl: "/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
query: { "sap-client": "100" },
});Create it from the generated model module, not from a $metadata parsed alone, when the service has value-help services: only the module holds them. See Generating models.
connectODataService
function connectODataService(
options: ODataConnectOptions,
init?: ODataSendInit,
): Promise<ODataService>;A low-level engine read from the live $metadata, for scripts and tools: reads $metadata through the transport (in language when the options name one), parses it, reads the value-help documents it references (v4 Common.ValueListReferences, the first of each property, all at once, with the same options and init) and merges them in. A value-help document that cannot be read leaves its properties without a value list; it fails nothing unless init.signal aborts. Throws ODataError when $metadata cannot be read and the parser's Error when the answer is not EDMX. It builds no types and compares nothing: an app connects a live source through its host instead.
createSession
function createSession(): ODataSession;A new, empty session: the cookies and CSRF tokens of one set of credentials. Pass it with a call (init.session) or as the transport's session option. In Node every write to an SAP service needs one, because the service binds its CSRF token to its session cookie. A live space of @atscript/db-odata keeps its sessions itself, one per credential its calls send (see ODataSessionOptions and Credentials and sessions); create one yourself in a script or a host of your own.
ODataService
interface ODataService {
readonly model: ServiceModel;
readonly context: ProtocolContext;
readonly transport: ODataTransport;
read(spec: ReadSpec, init?: ODataCallInit): Promise<ODataReadResult>;
readOne(
spec: ReadSpec & { key: Record<string, unknown> },
init?: ODataCallInit,
): Promise<ODataEntityResult | undefined>;
count(spec: ReadSpec, init?: ODataCallInit): Promise<number>;
aggregate(spec: AggregateSpec, init?: ODataCallInit): Promise<ODataAggregateResult>;
plan(spec: ReadSpec, init?: Pick<ODataCallInit, "read">): ReadPlan;
url(spec: ReadSpec, init?: Pick<ODataCallInit, "read">): string;
create(
entitySet: string,
data: Record<string, unknown>,
init?: Omit<ODataWriteInit, "etag">,
): Promise<ODataWriteResult>;
update(
entitySet: string,
key: Record<string, unknown>,
patch: Record<string, unknown>,
init?: ODataWriteInit,
): Promise<ODataWriteResult>;
replace(
entitySet: string,
key: Record<string, unknown>,
data: Record<string, unknown>,
init?: ODataWriteInit,
): Promise<ODataWriteResult>;
remove(
entitySet: string,
key: Record<string, unknown>,
init?: ODataWriteInit,
): Promise<ODataRemoveResult>;
call(
operation: string,
parameters?: Record<string, unknown>,
init?: ODataOperationInit,
): Promise<OperationResult>;
valueHelpService(key: string): ODataService | undefined;
batch(): ODataBatch;
}One OData service: its model, and reads and writes that go out as OData requests and come back decoded. It holds no state of its own; sessions and tokens live in the session a call is made with. The hosts call it for you; call it directly in scripts, jobs or a host of your own.
| Member | Does |
|---|---|
read | Reads a collection whole, following server-driven paging links until spec.top rows or the end. More than maxPages pages fail with ODataServiceError PAGE_LIMIT, never a partial result. With spec.count, a service that answers without the count is asked through /$count (filter and search). A filter that can never match answers empty without a call; an expansion whose filter can never match is left out and answered empty ([], null), and refused with UNSUPPORTED_ON_V2 on v2. |
readOne | Reads one entity by key; undefined when the service answers 404. Expansions as in read. |
count | /$count of the entities matching filter and search. |
aggregate | A grouped read as OData v4 $apply. Throws ODataQueryError UNSUPPORTED_AGGREGATE before any call when the set cannot be aggregated that way. See Aggregation. |
plan, url | What read would send, without sending it. |
create | POST to the entity set. Navigation members of data are created with it (deep insert). |
update | MERGE (v2) or PATCH (v4) of the members in patch. init.etag goes out as If-Match. |
replace | PUT of the whole entity. |
remove | DELETE of one entity; an entity already gone is an error (writeFailureOf answers not-found). |
call | Calls a v2 function import or a v4 function or action, unbound or bound through init.bound. The hosts call it for the db actions of a set and for odata.call: see Operations. |
valueHelpService | The engine of a value-help service of this one (by its key in model.valueHelpServices), created on first use with this service's options and session. undefined for an unknown key. |
batch | A new, empty ODataBatch: calls queued in it go out as one OData $batch when it is sent, whatever batch.auto, batch: false and BatchSupported say. Auto-batching and the browser client's createBatch() are built on it. |
Writes drop members the service maintains (computed ones always, immutable ones in an update or replace, update-only ones in a create) and report them in dropped. In Node a write needs an explicit session. See Writes and concurrency.
ODataBatch
interface ODataBatch extends ODataChangeset {
read(spec: ReadSpec, init?: ODataBatchCallInit): Promise<ODataReadResult>;
readOne(
spec: ReadSpec & { key: Record<string, unknown> },
init?: ODataBatchCallInit,
): Promise<ODataEntityResult | undefined>;
count(spec: ReadSpec, init?: ODataBatchCallInit): Promise<number>;
aggregate(spec: AggregateSpec, init?: ODataBatchCallInit): Promise<ODataAggregateResult>;
// create, update, replace, remove, call: as on ODataChangeset, each write a changeset of its own
changeset(): ODataChangeset;
hold(): () => void;
send(init?: ODataSendInit): Promise<PromiseSettledResult<unknown>[]>;
}Calls of one service queued to go out as one OData $batch, from service.batch(). Each method takes what the ODataService method of the same name takes, but for the session and the headers, and returns the same promise: once the batch is sent it settles as the call alone would, with the same result or the same error (readOne of a missing key is undefined, a 412 is changed to writeFailureOf). For scripts, jobs and a host of your own.
const order = { entitySet: "OrderSet", key: { OrderId: "1" } };
const batch = service.batch();
const page = batch.read({ entitySet: "OrderSet", top: 20, count: true });
const open = batch.count({ entitySet: "OrderSet", filter: { Status: "O" } });
const cs = batch.changeset(); // both writes or neither
const merged = cs.update("OrderSet", order.key, { Status: "R" }, { etag });
const released = cs.call("ReleaseOrder", {}, { bound: order });
const results = await batch.send({ session }); // one PromiseSettledResult per call, in call order| Member | Does |
|---|---|
| reads | read, readOne, count, aggregate, and a call of a function (an operation called with GET): each a part of its own. |
| writes | create, update, replace, remove, and a call of an action: each in a changeset of its own, so its failure rolls nothing else back. |
changeset | A new ODataChangeset at this place in the batch's order: the writes queued on it are applied all or none. |
hold | Keeps the batch from going out until the returned function is called. send waits for every open hold, so a call that still awaits something (a connection, a pre-read) joins the batch when it is made before its release. |
send | Sends the queued calls as one $batch (several when they hold more than batch.maxParts requests) with init's session, headers and signal; nothing when no call reached it, or when the signal aborts while a hold is open (every call then rejects as aborted). Resolves once every call has settled, with each call's outcome in call order. It does not reject for a call. Throws when called twice. |
- The parts go out in the order the calls (and the changesets) were made. A call that needs no request (a filter that can never match, an update with nothing left to write) or that the engine refuses before any request (
ODataWriteError,ODataQueryError) settles without joining the batch. - The
$batchrequest is a write, a batch of reads included: it fetches the CSRF token first. In Node a batch to a service that binds its token to a session cookie (an SAP service) needs a session (send({ session })), where the same reads sent alone need none. - A
$batchthe service refuses as a whole (a malformed body, a token still refused after the retry, a login page) rejects every call in it with that oneODataError, areadOneincluded. When the service has no$batchendpoint (404,405,501) the error hashint: "batch-unsupported", the service is marked as without$batchfor ten minutes, as by every other batch of it (batchAvailable), and a404of it is never a missing entity:readOnerejects instead of answeringundefined, andwriteFailureOfanswers nothing for it. - A call's follow-up requests (the paging links of
readandaggregate, the/$countof areadanswered without its count) go out alone after the batch, with the session and headers ofsend. - A call whose
signalaborts before the batch goes out is left out of it and rejects asaborted. In a changeset the whole changeset is left out with it, all or nothing: every call in it rejects asaborted, and so does a call queued on it later. After the batch has gone out only the call's own promise rejects: the service still runs its part. - A queued call takes no
sessionand noheaders(they aresend's): a call whoseinitbrings either throws aTypeError. - A write that fails, when the service answers its changeset as one error part (as SAP Gateway and SAP CAP answer a failed changeset), carries
changeseton its error:{ size: 1 }on v2 for a write on the batch itself,{ size: 1, contentId }on v4, or the shared changeset's size. Otherwise its error is the one it has alone. - After
send, once the batch has gone out, its methods,changesetandholdthrow: queue further calls in a new batch. - The wire format, Content-IDs and the resend of unanswered v4 parts are
sendBatch's, which the batch is sent with.
ODataChangeset
interface ODataChangeset {
create(
entitySet: string,
data: Record<string, unknown>,
init?: Omit<ODataBatchWriteInit, "etag">,
): Promise<ODataWriteResult>;
update(
entitySet: string,
key: Record<string, unknown>,
patch: Record<string, unknown>,
init?: ODataBatchWriteInit,
): Promise<ODataWriteResult>;
replace(
entitySet: string,
key: Record<string, unknown>,
data: Record<string, unknown>,
init?: ODataBatchWriteInit,
): Promise<ODataWriteResult>;
remove(
entitySet: string,
key: Record<string, unknown>,
init?: ODataBatchWriteInit,
): Promise<ODataRemoveResult>;
call(
operation: string,
parameters?: Record<string, unknown>,
init?: ODataBatchOperationInit,
): Promise<OperationResult>;
}The writes of one changeset of an ODataBatch, from batch.changeset(): the service applies them all or none. A changeset the service refuses rejects every call in it with the one error it answered, each with changeset: { size, contentId? } (ODataError). On v4 each call's details are the messages that name its Content-ID, and those that name none; v2 sends no Content-ID, so every call carries every message. A call of a function (GET) is a read, which a changeset cannot hold: it rejects with ODataWriteError UNSUPPORTED_IN_CHANGESET and is not sent.
sendEach
function sendEach<T>(
service: ODataService,
count: number,
call: (index: number, target: ODataEachTarget) => Promise<T>,
init?: ODataSendInit,
options?: { batch?: false; resend?: false },
): Promise<PromiseSettledResult<T>[]>;
type ODataEachTarget =
| { batch: ODataBatch; init?: undefined }
| { batch?: undefined; init: ODataSendInit & { batch: false } };Sends independent calls of one service, each on its own, as the hosts send an array insert and an operation on several rows: call(index, target) makes call index on its target (target.batch, or the service with target.init) and resolves as that call does. Where a $batch is available (batchAvailable), every call is made on one service.batch(), in index order, which is sent with init: each write queued on the batch itself is a changeset of its own, so its failure rolls nothing else back. A $batch that failed as a whole throws its error; one the service has no endpoint for (404, 405, 501) marks the service as without $batch (for its auto-batching too) and has the calls made again one by one, unless resend: false (then CHANGESET_WITHOUT_BATCH is thrown, its cause that answer). Otherwise the calls go one after the other with init and batch: false (so an auto-batching engine sends each alone), on past a failed one; with resend: false (calls only a $batch sends together, as a changeSet run) none is made and CHANGESET_WITHOUT_BATCH is thrown, also when the service was learned to have no $batch since the caller checked. Resolves each call's outcome in index order.
import { sendEach } from "@atscript/odata";
const outcomes = await sendEach(service, rows.length, (i, target) =>
target.batch
? target.batch.create("OrderSet", rows[i])
: service.create("OrderSet", rows[i], target.init),
);batchAvailable
function batchAvailable(service: ODataService, batch?: false): boolean;Whether sendEach sends the calls of service as one $batch: not with batch: false, not on a service created with batch: false, not on one whose model says it has none (Capabilities.BatchSupported false, or Supported false of Capabilities.BatchSupport), and not on one that answered a $batch 404, 405 or 501 in the last ten minutes (one sent by sendEach or by its auto-batching: one memory per service; then a $batch is tried again).
ODataServiceOptions
type ODataServiceOptions = ODataServiceSettings &
ODataServiceTransportOptions & {
/** The service model, generated at build time or parsed by the host. */
model: ServiceModel;
};The options of createODataService.
ODataConnectOptions
type ODataConnectOptions = ODataServiceSettings &
ODataServiceTransportOptions & {
/** Receives everything the $metadata parser tolerated instead of failing on. */
onWarning?: (warning: ParseWarning) => void;
/** The language to read the metadata documents in ($metadata and value-help documents). */
language?: string;
};The options of connectODataService, and the base of ODataSourceOptions. language (an SAP code such as EN, or a tag such as en) is sent as the query option sap-language and the header Accept-Language with the metadata reads only, over a sap-language of query and an Accept-Language of the headers; data calls are not affected. Absent: none is asked for, and the service picks one. See The language.
ODataServiceTransportOptions
type ODataServiceTransportOptions = Omit<ODataTransportOptions, "version" | "dialect" | "batch"> & {
/** Wire dialect preset. Default: the one the model fits (`sap` for SAP Gateway and RAP, else `standard`). */
dialect?: ODataDialectName;
/** $batch settings: maxParts (the transport's), auto (the engine's auto-batching); false: no $batch of its own. */
batch?: false | { maxParts?: number; auto?: boolean };
};What the engine creates its transport from. The fields of ODataTransportOptions it keeps:
| Option | Default | Meaning |
|---|---|---|
baseUrl | required | Service root, absolute (https://host/sap/opu/odata/sap/ZSRV) or root-relative (/sap/opu/odata/sap/ZSRV). |
dialect | from the model | "sap" or "standard". See Dialects and vendors. |
fetch | globalThis.fetch | The fetch to call, looked up at call time. |
headers | none | Static headers, or an ODataHeadersHook called for every HTTP call, the CSRF fetch included. |
credentials | none | Passed to fetch; relevant in browsers only. |
csrf | true | CSRF token handling for unsafe methods; { ttl } sets how long a token is reused (default DEFAULT_CSRF_TTL). A token fetch answered without a token is not repeated for ttl; one answered 404, 405 or 501 (no token endpoint) not for ten minutes, for every session of the transport, unless a write is refused for want of a token. |
session | none | The session a call that names none uses. Supply it when every call acts for one user (a browser app, one technical user). |
query | none | Query options appended to every call, $metadata and the CSRF fetch included (sap-client). A metadata read with a language asks for it over a sap-language here. |
merge | "verb" | How a v2 MERGE is sent: the MERGE verb, or "tunnel" as POST with X-HTTP-Method: MERGE for proxies that refuse it. |
batch | { maxParts: 100 } | $batch settings: maxParts is how many requests one $batch carries at most (see sendBatch); auto: true turns on auto-batching (below). false: no $batch of the engine's own (below). |
Auto-batching (batch: { auto: true }, what the browser client factory sets by default): the engine collects the calls made in one synchronous pass with the same session and headers, and sends them on the next macrotask (setTimeout(0)) as one $batch on batch(), each read a part of its own and each write (an action included) a changeset of its own, in the order they queued. A pass with one call sends it alone. Each call settles as it would alone; its follow-ups (a paging link, the /$count of a read answered without its count) go out alone after the batch. A call with batch: false (ODataCallInit) is never collected.
- Off where the model's container says
Capabilities.BatchSupportedis false. - From the first
$batchthe service answers404,405or501(no batch endpoint), the calls of that batch are sent again one by one, and nothing is collected for ten minutes (then a$batchis tried again). A$batchrefused otherwise (a malformed body, a login page) rejects every call in it. - The engine of a value-help service (
valueHelpService) inherits the option and batches at its own root. - For a browser, where every call acts for one user. Not on a server acting for several end users: a
$batchgoes out after its calls were made, so aheadersfunction is called outside the call that needed it. The Moost server's space never auto-batches.
batch: false: the engine makes no $batch of its own, as on a service without one: no auto-batching, and the calls sent together (sendEach: an array insert, an operation on several rows) go one after the other (batchAvailable is false); an operation on several rows applied all or none is refused (CHANGESET_WITHOUT_BATCH). A batch you make yourself (batch()) still goes out as one. The engines of its value-help services take it too. A space's and a browser registration's batch: false create their services so.
ODataServiceSettings
interface ODataServiceSettings {
/** Defaults for building read requests; a call may override single options. */
read?: ReadRequestOptions;
/** The most HTTP calls one read makes while following paging links. Default DEFAULT_MAX_PAGES. */
maxPages?: number;
/** Defaults for building write and operation requests. */
write?: WriteRequestOptions;
/** false: an entity set is searchable only where the metadata says so. */
search?: false;
}search: false: an entity set is searchable only where its metadata says so (a Capabilities.SearchRestrictions record whose Searchable is not false, v2 sap:searchable="true": EntitySetCapabilities.searchDeclared), not by the OData v4 default, which takes every set without SearchRestrictions as searchable. For a v4 service that refuses $search and declares nothing (Northwind and other services built on WCF Data Services or ASP.NET Web API): the engine's model (service.model) then gives such sets searchable: false, /meta of both hosts says so (Atscript UI shows no search box), and a search is refused before any request (ODataQueryError NOT_SEARCHABLE). The engines of its value-help services take it too. On v2 it changes nothing: a v2 set is searchable only by sap:searchable. A space and a browser registration take it as one of their options.
ODataSendInit
interface ODataSendInit {
/** The caller's state: cookies are stored in it and sent from it, its CSRF token reused. */
session?: ODataSession;
signal?: AbortSignal;
/** Headers for this call; they win over every other source. */
headers?: Record<string, string>;
}Per-call options every engine method takes, through the init types below. This is where a host puts the credentials and the session of a call. Calls of one session share its CSRF token whatever headers they carry: pass different credentials with different sessions.
ODataCallInit
interface ODataCallInit extends ODataSendInit {
/** Overrides single read options of the service for this call. */
read?: ReadRequestOptions;
/** Page limit of this call, in place of the service's maxPages. */
maxPages?: number;
/** false: never auto-batched, the call goes out alone. */
batch?: false;
}The per-call options of reads (batch as on every init type: see auto-batching), and what the init of createODataSpace and the call option of the browser client return.
ODataWriteInit
interface ODataWriteInit extends ODataSendInit {
/** Overrides single write options of the service for this call. */
write?: WriteRequestOptions;
/** Update, replace, delete: the ETag sent as If-Match; "*" overwrites whatever is there. */
etag?: string;
/** false: never auto-batched, the call goes out alone. */
batch?: false;
}Without etag no If-Match is sent, also on an entity set that declares optimistic concurrency; the service's refusal is then recognised by writeFailureOf.
ODataOperationInit
interface ODataOperationInit extends ODataSendInit {
write?: WriteRequestOptions;
/** The entity (with key) or entity set the operation is called on. */
bound?: { entitySet: string; key?: Record<string, unknown> };
/** The ETag of the entity the operation is called on, sent as If-Match. */
etag?: string;
/** false: never auto-batched, the call goes out alone. */
batch?: false;
}ODataBatchCallInit
type ODataBatchCallInit = Omit<ODataCallInit, "session" | "headers" | "batch">;
type ODataBatchWriteInit = Omit<ODataWriteInit, "session" | "headers" | "batch">;
type ODataBatchOperationInit = Omit<ODataOperationInit, "session" | "headers" | "batch">;The per-call options of a read, a write and an operation call queued in an ODataBatch: those that shape the request (read, maxPages, write, etag, bound) and the call's signal. The session and the headers are those of send, since one $batch is one HTTP request: a call whose init brings either (a variable typed ODataCallInit passes the type check) throws a TypeError.
ODataReadResult
interface ODataReadResult {
/** Decoded entities: Atscript-side values, no protocol control information. */
rows: Record<string, unknown>[];
/** Total count, when the service reported one with the first page. */
count?: number;
/** ETag per row, in row order; absent when no entity carried one. */
etags?: (string | undefined)[];
/** Inline counts of expanded to-many navigations per row, keyed by navigation path. */
expandCounts?: (Record<string, number> | undefined)[];
}ODataEntityResult
interface ODataEntityResult {
row: Record<string, unknown>;
/** From the payload, else from the ETag response header. */
etag?: string;
expandCounts?: Record<string, number>;
}ODataAggregateResult
interface ODataAggregateResult {
/** One row per group: the grouped properties and each aggregate under its alias. */
rows: Record<string, unknown>[];
/** The number of groups, when the spec asked for it. */
count?: number;
}ODataWriteResult
interface ODataWriteResult extends WriteResult {
/** Payload members not sent because they may not be written. Absent when everything was sent. */
dropped?: string[];
/** An update or replace sent no request: every member was dropped. */
skipped?: true;
}
interface WriteResult {
/** The entity as returned: after a create, and after an update only on v4 when asked for. */
row?: Record<string, unknown>;
/** The new ETag, from the payload or the ETag header. */
etag?: string;
/** The key, from the returned entity or the OData-EntityId / Location header. */
key?: Record<string, unknown>;
/** The Location (or OData-EntityId) header. */
location?: string;
/** Messages the service attached (sap-message / sap-messages). */
messages?: ODataMessage[];
}WriteResult is exported too; it is what readWriteResponse reads from an answer.
ODataRemoveResult
interface ODataRemoveResult {
/** Messages the service attached to the answer. */
messages?: ODataMessage[];
}OperationResult
interface OperationResult {
/** The returned value decoded by the declared return type; undefined when nothing is returned. */
value: unknown;
etag?: string;
messages?: ODataMessage[];
}What ODataService.call resolves with.
ReadSpec
interface ReadSpec {
entitySet: string;
/** Read one entity by key; then only select and expand apply. */
key?: Record<string, unknown>;
filter?: FilterExpr; // Uniquery filter of @uniqu/core
/** Property paths to return; key properties are always added. */
select?: string[];
orderBy?: OrderBySpec[];
skip?: number;
top?: number;
/** Ask for the total count alongside the page. */
count?: boolean;
/** Free-text search. */
search?: string;
expand?: ExpandSpec[];
}
interface OrderBySpec {
path: string;
desc?: boolean;
}
interface ExpandSpec extends Pick<
ReadSpec,
"filter" | "select" | "orderBy" | "skip" | "top" | "count" | "expand"
> {
/** Navigation property name on the parent. */
navigation: string;
}A version-neutral read of one entity set. readSpecFromUniquery builds one from a Uniquery.
AggregateSpec
interface AggregateSpec {
entitySet: string;
filter?: FilterExpr;
/** Property paths to group by; [] is one group over every matching row. */
groupBy: string[];
aggregates: AggregateEntry[];
/** A filter on the groups: its keys are grouped paths and aliases. */
having?: FilterExpr;
orderBy?: OrderBySpec[];
skip?: number;
top?: number;
/** Ask for the number of groups. */
count?: boolean;
/** Refused: $apply is not combined with a search. */
search?: string;
}
interface AggregateEntry {
/** An AggregateFunction; anything else is refused. */
fn: string;
/** The property path to aggregate; "*" for count. */
field: string;
/** The key of the column in the result rows. */
alias: string;
}
type AggregateFunction = "sum" | "min" | "max" | "avg" | "count" | "countDistinct";A grouped read as OData v4 $apply expresses it. See Aggregation.
OperationSpec
interface OperationSpec {
/** Import name, local name or qualified name. */
operation: string;
parameters?: Record<string, unknown>;
/** One entity (key given) or the collection of an entity set (no key). */
bound?: { entitySet: string; key?: Record<string, unknown> };
etag?: string;
}ReadRequestOptions
interface ReadRequestOptions {
/** Add the unit or currency property of every selected amount or quantity to $select. Default true. */
selectUnits?: boolean;
}WriteRequestOptions
interface WriteRequestOptions {
/** v4: ask for the entity in the answer (Prefer: return=representation) or not (return=minimal). */
returnEntity?: boolean;
}OData v2 has no way to ask: a create answers with the entity anyway, an update or replace never does.
ODataSession
interface ODataSession {
/** Captured cookies: origin of the service root → cookie name → value. */
cookies: Record<string, Record<string, string>>;
/** CSRF state by service root URL. */
csrf: Record<string, ODataCsrfState>;
}
interface ODataCsrfState {
/** Absent when the service answered the token fetch without a token. */
token?: string;
/** Date.now() at the start of the token fetch. */
fetchedAt: number;
}Plain data, created with createSession. Cookies are scoped by origin, so several services can share one session without sending one host's cookies to another.
ODataFetch
type ODataFetch = (url: string, init: RequestInit) => Promise<Response>;The part of fetch the transport uses. Inject one for tests, a proxy agent or logging.
ODataHeadersHook
type ODataHeadersHook = (
request: ODataRequest,
) => Record<string, string> | Promise<Record<string, string>>;Headers for one outgoing HTTP call, the CSRF token fetch included. An error it throws reaches the caller unchanged. With a hook and no session, no CSRF token is cached between calls, since each call may act for another user.
DEFAULT_MAX_PAGES
const DEFAULT_MAX_PAGES = 100;How many pages one read follows before it fails with PAGE_LIMIT, unless maxPages says otherwise.
DEFAULT_CSRF_TTL
const DEFAULT_CSRF_TTL = 180000; // three minutesHow long a fetched CSRF token is reused before a new one is fetched.
VERSION_TOKEN
const VERSION_TOKEN = "__etag";The name of the version token field the generator gives an entity set with optimistic concurrency (@db.column.version.token): a row read carries its entity's ETag in it, and a write or an operation call on the row sends it as If-Match. A set whose entity type has a property of that name gets no token (the plan reports it). Read it rather than spelling the name.
Metadata
parseMetadata
function parseMetadata(xml: string, options?: ParseMetadataOptions): ServiceModel;
interface ParseMetadataOptions {
/** Called for everything the parser tolerated instead of failing on. */
onWarning?: (warning: ParseWarning) => void;
}
interface ParseWarning {
code: ParseWarningCode;
message: string;
}
type ParseWarningCode =
| "unresolved-annotation-target"
| "unresolved-navigation"
| "unresolved-operation-import"
| "unresolved-type";Parses a $metadata document (EDMX, OData v2 or v4) into the normalized, version-neutral ServiceModel. Unknown elements and attributes are ignored. Throws Error for input that is not EDMX, has no Schema, or declares an EDMX version other than 1.0, 4.0 or 4.01. The hosts parse the live document only on the slow path of a live source: when it matches the saved one, nothing is parsed.
odataVersionFromEdmx
function odataVersionFromEdmx(edmxVersion: string): ODataVersion;
type ODataVersion = "v2" | "v4";Maps the Version attribute of edmx:Edmx to the protocol generation: 1.0 is v2, 4.0 and 4.01 are v4.
mergeValueHelps
function mergeValueHelps(
model: ServiceModel,
documents: Record<string, ValueHelpDocument | undefined>,
): ServiceModel;
type ValueHelpDocument = string | { error: string };Adds the value lists of Common.ValueListReferences documents (SAP RAP value-help services) to a model and returns a new model; the given one is unchanged. The documents are keyed by the reference as the $metadata writes it. A property whose first reference's document is missing, unreadable or holds no mapping keeps no value list and says why in valueListReferenceProblem; nothing fails. The plugin and the hosts do this for you. See Value helps.
valueHelpReferences
function valueHelpReferences(model: ServiceModel): string[];The value-help documents a model needs: the first Common.ValueListReferences URL of every property that has no value list of its own, each once, in model order.
valueHelpTarget
function valueHelpTarget(reference: string): ValueHelpTarget | undefined;
interface ValueHelpTarget {
/** The root of the value-help service relative to the referencing service's root. */
path: string;
/** Its name in ServiceModel.valueHelpServices: the path without matrix parameters. */
key: string;
}Where a value-list reference leads; undefined when it is no URL of a $metadata document.
Types at runtime
The plugin writes .as files at build time. These functions build the same annotated types in memory: what a live source uses for runtime-only mode (a registration without model) and, on the slow path, to rebuild the generated classes in place.
buildServiceTypes
function buildServiceTypes(
model: ServiceModel,
options: PlanOptions,
): { types: BuiltTypes; plan: ServicePlan };
interface PlanOptions {
/** Service name, written as @db.space on every entity set interface. */
service: string;
/** Limit to these entity sets and what their interfaces reference. Default: all. */
entitySets?: string[];
/** Operations left out: import, local or qualified names. Drafts are always left out. */
operations?: { exclude?: string[] };
}
type BuiltTypes = Record<string, TAtscriptAnnotatedType>;Plans a service and builds its types: planService then buildTypes. The types are those the Atscript compiler produces from the .as file the plugin writes for the same model, the operation types (<Name>Params) included; plan.skipped lists what they leave out, plan.operations the selected operations.
import { buildServiceTypes, createODataService, parseMetadata } from "@atscript/odata";
const model = parseMetadata(xml);
const service = createODataService({
model,
baseUrl: "https://host/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
});
const { types } = buildServiceTypes(model, { service: "sales" });
// types.Order, types.Customer, ...buildTypes
function buildTypes(plan: ServicePlan, options?: BuildTypesOptions): BuiltTypes;
interface BuildTypesOptions {
/** Existing declarations to build into, by name: the classes of a compiled module. */
into?: Record<string, unknown>;
}Builds the annotated types of a plan. Without into, each call builds new type objects. With into, a declaration of the plan that has an annotated type of its name there is rebuilt in place (the same object, its own metadata replaced), as the compiled module fills its classes; one without gets a new object. References between the declarations (foreign keys, navigations, value helps) point to the returned objects. A live source builds into the generated module on the slow path.
planService
function planService(model: ServiceModel, options: PlanOptions): ServicePlan;Decides what to emit for a service: interfaces, aliases, their properties, types and annotations, and what is left out. Every mapping decision of the generator is taken here; printAs and buildTypes only render the plan.
printAs
function printAs(plan: ServicePlan, options?: { notes?: readonly string[] }): string;Writes a plan as Atscript source: the .as file the plugin writes, including the trailing list of what the types cannot express. notes are lines of the trailer after that list, each written as // Note: … (the plugin adds one when a service names no language). The same plan and notes always give the same text.
printModelModule
function printModelModule(
model: ServiceModel,
service: string,
options?: PrintModelOptions,
): string;
interface PrintModelOptions {
/** The plan the .as file was printed from: its operations become the ops handles. */
plan?: ServicePlan;
/** How the module imports the .as file, type-only ("./sales.as"). Required with a plan that has operations. */
types?: string;
}Writes a model as the TypeScript module the plugin writes (export const model: ServiceModel, also the default export). The model is held as JSON text and parsed when the module loads, a parse marked pure. With a plan, the module also exports ops: an ODataOperationRef per selected operation with its paramsType, typed by the declarations of types, imported type-only as a namespace (import type * as T), so no declaration name of the service collides with the module's own. The plugin sets model.build before it writes the module (see ServiceModelBuild).
printControllersModule
function printControllersModule(
plan: ServicePlan,
model: ServiceModel,
options: PrintControllersOptions,
): PrintedControllers;
interface PrintControllersOptions {
/** How the module imports the .as file ("./sales.as"). */
types: string;
/** How the module imports the model module ("./sales.model.gen"), for the ops handles. */
model: string;
/** Entity sets whose base extends ODataTableController; the others ODataReadableController. */
writable?: readonly string[];
}
interface PrintedControllers {
text: string;
/** Every db action of the set bases: { entitySet, route, operation, level }. */
actions: PrintedAction[];
/** Every route of the operations base: { route, operation }. */
operations: PrintedRoute[];
}Writes the controllers module of a Moost server, as the plugin's controllers option does: a base per entity set with operations bound to its type (<EntitySet>Base, its db actions op_<Name> at actions/<Name>, with Moost DB's decorators and @ODataOperation) and, when the service has unbound operations, its operations base (<Service>OperationsBase, a POST route <Name> each). model is the model the plan was made of: the operations' grouping and the sets' required filters come from it. See Operations.
opsLayout
function opsLayout(plan: Pick<ServicePlan, "operations">): OpsLayout;
interface OpsLayout {
/** Unbound operations, keyed by import name. */
unbound: { key: string; op: PlanOperation }[];
/** Bound operations by entity set: the set's key, and each operation's key by local name. */
sets: { entitySet: string; key: string; entries: { key: string; op: PlanOperation }[] }[];
}Where each selected operation stands in the model module's ops: an unbound one by import name, a bound one under its entity set by local name, _ appended to a taken name (the entity sets claim their keys first). A bound operation's key is also the name of its db action, on a Moost server's generated base and in the browser client. Pass a plan, or { operations: operationsOf(connection) } for what a connection runs.
pruneModel
function pruneModel(model: ServiceModel, options?: PruneModelOptions): ServiceModel;
interface PruneModelOptions {
/** Limit to these entity sets and their closure, as planService does. */
entitySets?: string[];
/** Operations left out, as planService takes them. */
operations?: { exclude?: string[] };
}A smaller model for shipping to a browser: limited to a selection of entity sets and without raw annotations. Its operations are exactly the selected ones: no draft lifecycle operation, none excluded, none the plan lists as skipped. The result is self-consistent; the given model is unchanged. The plugin applies it to the model module.
Dialects
dialectFor
function dialectFor(model: Pick<ServiceModel, "vendor">, name?: ODataDialectName): ODataDialect;The dialect to use for a service: the preset named, else the one the model fits. This is what the engine applies when dialect is not given.
defaultDialectName
function defaultDialectName(model: Pick<ServiceModel, "vendor">): ODataDialectName;"sap" for a document an SAP Gateway or RAP service produced (model.vendor === "sap"), "standard" for every other service, SAP CAP included.
resolveDialect
function resolveDialect(name?: ODataDialectName): ODataDialect;The switches of a preset, as a fresh object. Without a name it answers the standard preset, as dialectFor does for a model that is no SAP document; use dialectFor to follow the model.
ODataDialectName
type ODataDialectName = "sap" | "standard";ODataDialect
interface ODataDialect {
caseInsensitive: "ignore" | "tolower";
emptyStringIsNull: boolean;
v2NumericSuffixes: boolean;
v4SearchTerm: "raw" | "phrase";
v2OperationContentType: boolean;
}| Switch | sap | standard | Decides |
|---|---|---|---|
caseInsensitive | "ignore" | "tolower" | How a case-insensitive pattern is sent: as written (upper-cased for upper-case-only fields), or wrapped in tolower() |
emptyStringIsNull | true | false | $exists on a string also tests '' (ABAP character fields are never null) |
v2NumericSuffixes | false | true | v2 numeric literals carry L / M / d / f |
v4SearchTerm | "raw" | "phrase" | v4 $search sends the term as typed, or as one quoted phrase |
v2OperationContentType | false | true | A v2 function import that is no GET declares Content-Type: application/json |
Presets only: there are no partial overrides. See Dialects and vendors.
ProtocolContext
interface ProtocolContext {
version: ODataVersion;
dialect: ODataDialect;
}What a codec or planning function needs to know about the service: service.context.
Capabilities and write rules
describeEntitySet
function describeEntitySet(
model: ServiceModel,
entitySet: string,
ctx: ProtocolContext,
): EntitySetDescription;The set-level facts a host's metadata is built from: what a read may ask for, the key and the key properties it can be sorted by, the navigations, the writes the service declares, draft, optimistic concurrency and aggregation. Throws ODataQueryError UNKNOWN_ENTITY_SET.
describeField
function describeField(
model: ServiceModel,
target: FieldTarget,
path: string,
ctx: ProtocolContext,
): FieldDescription;
type FieldTarget = string | { entityType: string };What a read may do with one property path: whether it can be filtered, sorted and grouped by, and with which operators. "Yes" here is exactly "the read planner accepts it". An unknown path is described as unknown with nothing allowed; it does not throw.
writeRefusal
function writeRefusal(
set: Pick<
EntitySetDescription,
"name" | "addressable" | "draft" | "parameters" | "insertable" | "updatable" | "deletable"
>,
write: EntitySetWrite,
): ODataWriteError | undefined;
type EntitySetWrite = "insert" | "update" | "delete";Why a write is refused on an entity set, as an ODataWriteError (NOT_ADDRESSABLE, DRAFT_NOT_SUPPORTED, NOT_INSERTABLE, NOT_UPDATABLE, NOT_DELETABLE), or undefined when it is allowed. The one rule the engine, the browser client and the Moost server refuse writes by. It reads seven facts of the set's describeEntitySet description: pass the description, or just those.
allowedWrites
function allowedWrites(set: EntitySetDescription): Record<EntitySetWrite, boolean>;The writes a host may offer: those writeRefusal does not refuse. The browser client's meta and ODataTableController's /meta list exactly these in crud.
EntitySetDescription
interface EntitySetDescription {
name: string;
entityType: string;
/** Readable from the service root; otherwise only through an expansion. */
addressable: boolean;
filterable: boolean;
sortable: boolean;
searchable: boolean;
countable: boolean;
/** Functions of a grouped read; empty when the set cannot be aggregated. */
aggregateFns: AggregateFunction[];
/** Advisory: reads are sent without the filter. */
requiresFilter: boolean;
requiredFilters: string[];
key: string[];
/** The key properties the set can be sorted by: what paged reads are ordered by. */
sortableKey: string[];
navigations: NavigationDescription[];
insertable: boolean;
updatable: boolean;
deletable: boolean;
/** Draft-enabled (Common.DraftRoot / DraftNode): read for active entities, not written. */
draft?: "root" | "node";
/** Optimistic concurrency: present when declared (an empty list declares it without properties). */
optimisticConcurrency?: string[];
/** Holds the parameters of a parameterized view. */
parameters: boolean;
}
interface NavigationDescription {
name: string;
target: string;
collection: boolean;
expandable: boolean;
/** $some / $none can be used on it (v4, and the set allows it). */
filterable: boolean;
}FieldDescription
interface FieldDescription {
path: string;
kind: "property" | "navigation" | "unknown";
property?: PropertyModel;
navigation?: NavigationModel;
filterable: boolean;
sortable: boolean;
groupable: boolean;
/** Operators the query layer can translate for this property on this OData version. */
filterOps: FieldOperator[];
/** filterOps narrowed by the service's filter restriction: what a filter UI should offer. */
allowedFilterOps: FieldOperator[];
filterRestriction?: FilterRestriction;
/** Advisory, not enforced. */
requiredInFilter: boolean;
caseInsensitivePatterns: boolean;
}
type FieldOperator =
| "$eq"
| "$ne"
| "$gt"
| "$gte"
| "$lt"
| "$lte"
| "$in"
| "$nin"
| "$exists"
| "$regex"
| "$some"
| "$none";aggregateFunctions
function aggregateFunctions(set: EntitySetModel, model: ServiceModel): AggregateFunction[];The functions a grouped read of the set may use: none on OData v2, without Aggregation.ApplySupported or on a set that is not addressable; sum, min, max, avg on an SAP service; all six on any other.
Errors
Every error class has an is… guard that is also true for an instance created by another copy of the package; prefer the guards over instanceof. How the hosts turn these into HTTP answers is on the Errors page.
ODataError
class ODataError extends Error {
readonly name: "ODataError";
readonly kind: ODataErrorKind;
/** HTTP status; 0 when there was no response. */
readonly status: number;
/** Error code of the service. */
readonly code?: string;
/** v4: what the leading error refers to. */
readonly target?: string;
readonly severity?: string;
/** The detail messages the service listed, in its order. */
readonly details: ODataMessage[];
readonly body: unknown;
readonly headers: Record<string, string>;
/** The HTTP call that failed (the token fetch for a failed CSRF fetch). */
readonly request: ODataRequestLine;
readonly hint?: ODataErrorHint;
/** Set when the request was part of a `$batch` changeset the service refused as a whole. */
readonly changeset?: ODataChangesetFailure;
/** v4 `$batch`: the Content-ID the error itself names (`@Core.ContentID`, as SAP CAP writes it). */
readonly contentId?: string;
constructor(init: ODataErrorInit);
}
type ODataErrorKind = "http" | "network" | "aborted" | "unexpected-content" | "csrf";
type ODataErrorHint = "session-required" | "batch-unsupported" | "redirected";
interface ODataRequestLine {
method: string;
url: string;
/** The If-Match the call was sent with: `*`, an ETag, or none. */
ifMatch?: string;
}
interface ODataChangesetFailure {
/** How many requests the changeset held: each rejects with this error. */
size: number;
/** v4: the request's Content-ID; its `details` are then the messages naming it or none. */
contentId?: string;
}The HTTP exchange failed. kind: http (a status outside 2xx), csrf (the token was still refused after a fresh fetch), unexpected-content (a 2xx that is not what was asked for, typically a login page; a redirect answering an unsafe request, status 3xx, 0 in a browser, with hint: "redirected": a write or a $batch is never sent on to another address, while GET and HEAD follow redirects; a part of a $batch answer that cannot be read, status 0), network (no answer: connection, DNS, CORS, TLS), aborted (the signal fired or the call timed out). hint: "session-required" means a write ran without a session, so the cookie its CSRF token is bound to was lost; hint: "batch-unsupported" means a $batch was answered 404, 405 or 501: the service has no batch endpoint, send the requests one by one; hint: "redirected" marks the redirect of an unsafe request (sign in again: the browser client answers it 401 UNEXPECTED_CONTENT). request (ODataRequestLine, exported) names the call, with the If-Match it carried, which tells a 412 apart (writeFailureOf): to an ETag a change, to * an entity gone, to none a precondition the service demands. changeset is set on the error of each request of a $batch changeset the service refused as a whole: none of them was applied, and each carries the same status and message. ODataErrorInit is the constructor's argument (the fields above plus message and cause).
ODataQueryError
class ODataQueryError extends Error {
readonly name: "ODataQueryError";
readonly code: ODataQueryErrorCode;
/** The property, navigation or control the error is about. */
readonly path?: string;
constructor(
code: ODataQueryErrorCode,
message: string,
details?: { path?: string; cause?: unknown },
);
}
type ODataQueryErrorCode =
| "UNKNOWN_ENTITY_SET"
| "UNKNOWN_PROPERTY"
| "UNKNOWN_NAVIGATION"
| "UNSUPPORTED_FILTER"
| "UNSUPPORTED_REGEX"
| "UNSUPPORTED_ON_V2"
| "UNSUPPORTED_EXPAND"
| "UNSUPPORTED_SELECT"
| "UNSUPPORTED_CONTROL"
| "UNSUPPORTED_AGGREGATE"
| "INVALID_VALUE"
| "INVALID_KEY"
| "NOT_ADDRESSABLE"
| "NOT_FILTERABLE"
| "NOT_SORTABLE"
| "NOT_SEARCHABLE"
| "NOT_COUNTABLE"
| "NOT_EXPANDABLE"
| "MATCHES_NOTHING";A read cannot be turned into an OData request: the name is unknown (UNKNOWN_*), OData or this OData version cannot express it (UNSUPPORTED_*), the model says the set does not allow it (NOT_*), or a value does not fit its type. Thrown before any request. The codes are stable.
ODataWriteError
class ODataWriteError extends Error {
readonly name: "ODataWriteError";
readonly code: ODataWriteErrorCode;
/** A payload path (Items.0.Product), a parameter, an entity set or an operation. */
readonly path?: string;
constructor(
code: ODataWriteErrorCode,
message: string,
details?: { path?: string; cause?: unknown },
);
}
type ODataWriteErrorCode =
| "UNKNOWN_ENTITY_SET"
| "UNKNOWN_PROPERTY"
| "UNKNOWN_NAVIGATION"
| "UNKNOWN_OPERATION"
| "UNKNOWN_PARAMETER"
| "NOT_INSERTABLE"
| "NOT_UPDATABLE"
| "NOT_DELETABLE"
| "NOT_ADDRESSABLE"
| "DRAFT_NOT_SUPPORTED"
| "UNSUPPORTED_DEEP_UPDATE"
| "UNSUPPORTED_NAVIGATION"
| "UNSUPPORTED_PARAMETER"
| "UNSUPPORTED_IN_CHANGESET"
| "MISSING_PARAMETER"
| "AMBIGUOUS_OPERATION"
| "INVALID_BINDING"
| "INVALID_VALUE"
| "INVALID_KEY"
| "DECLARED_PARAMETER"
| "OPERATION_GONE"
| "CHANGESET_WITHOUT_BATCH";A write or operation call cannot be turned into a request: the model refuses it or the payload does not fit. Thrown before any request. UNSUPPORTED_IN_CHANGESET: a function was queued in a $batch changeset, which holds writes and actions only. From runOperation:
| Code | Meaning |
|---|---|
DECLARED_PARAMETER | extra names a parameter the operation declares: give it in params. |
OPERATION_GONE | The live service no longer has the operation the build was made for (a refusal of a source created with verdicts). |
CHANGESET_WITHOUT_BATCH | An operation called on several rows as one changeset (changeSet) with no $batch to send it in (batch: false, a service without $batch): one call after the other cannot be applied all or none. dbFailureOf answers NOT_SUPPORTED. |
ODataServiceError
class ODataServiceError extends Error {
readonly name: "ODataServiceError";
readonly code: ODataServiceErrorCode;
/** The paging link the error is about, as sent. */
readonly link?: string;
}
type ODataServiceErrorCode = "PAGE_LIMIT" | "PAGING_LINK" | "IF_MATCH_REFUSED";A call the engine gave up on: a read past maxPages pages (PAGE_LIMIT) or along a paging link that leads nowhere in the service (PAGING_LINK), or a write by key the service refuses whatever is sent (IF_MATCH_REFUSED: its read found the entity without an ETag, the service answered the If-Match: * sent instead with 412, and a further read finds the entity there; the 412 is the cause). The Moost server answers it 502 STORE_FAILED (PAGE_LIMIT: 400 INVALID_QUERY), the browser client a TransportError.
ODataValueError
class ODataValueError extends Error {
readonly name: "ODataValueError";
readonly code: ODataValueErrorCode;
readonly edmType?: string;
readonly property?: string;
}
type ODataValueErrorCode = "INVALID_VALUE" | "MISSING_KEY";A value cannot be written as an OData literal or payload value of its type, or a key property is missing.
ODataPayloadError
class ODataPayloadError extends Error {
readonly name: "ODataPayloadError";
readonly code: "INVALID_PAYLOAD";
}A response body without the envelope its OData version prescribes: a collection or an entity that is none (a collection answer is no entity), an operation's v4 value without value.
isODataError
function isODataError(value: unknown): value is ODataError;
function isODataQueryError(value: unknown): value is ODataQueryError;
function isODataWriteError(value: unknown): value is ODataWriteError;
function isODataServiceError(value: unknown): value is ODataServiceError;
function isODataValueError(value: unknown): value is ODataValueError;
function isODataPayloadError(value: unknown): value is ODataPayloadError;The guards of the classes above (isODataQueryError, isODataWriteError, isODataServiceError, isODataValueError, isODataPayloadError share this entry).
writeFailureOf
function writeFailureOf(error: unknown): ODataWriteFailure | undefined;
type ODataWriteFailure = "not-found" | "changed" | "etag-required";Classifies a failed write by its HTTP status and, for a 412, the If-Match the request carried (ODataError.request.ifMatch): not-found (404, 410, and a 412 to If-Match: *, which holds for any entity that exists: the entity is gone), changed (412 to an ETag: the entity changed since that ETag was read), etag-required (428, or a 412 to a request without If-Match: the service wants a precondition and got none). Two errors are none of them, since they say nothing about what one request addresses: a $batch answered 404 because the service has no batch endpoint (hint: "batch-unsupported"), and the error of a changeset of several requests (changeset.size over 1), whose 404 or 412 to an ETag may be another request's. So a host neither reads such an error as its own row missing or changed nor sends its write again alone (retryWhileChanged). A 412 to * or to no If-Match names no ETag that changed, and reads alike in a changeset; dbFailureOf answers a changeset's 412 to * as its 404 (CONFLICT) and leaves one to no If-Match to the host, as a 428. See Writes and concurrency.
isNotFoundError
function isNotFoundError(error: unknown): boolean;The service answered that what the request addresses does not exist.
isConcurrencyError
function isConcurrencyError(error: unknown): boolean;The write failed on optimistic concurrency (412 or 428): read again before writing.
retryWhileChanged
function retryWhileChanged<T>(attempt: () => Promise<T>): Promise<T>;Sends a last-write-wins write the way both hosts do: attempt reads the entity's current ETag and sends the write with it as If-Match; while the service answers 412 to that ETag (the entity changed between that read and the write; writeFailureOf changed), attempt runs again, three times in all. Only for an attempt that reads the ETag itself: nothing else changes between two attempts. The last attempt's 412 is thrown, which dbFailureOf answers as SERIALIZATION_FAILURE; any other failure is thrown at once. Not for a write with the caller's version token, where a 412 is the caller's version mismatch.
changeByKey
function changeByKey(
write: (etag: string | undefined) => Promise<unknown>,
options: {
/** Reads the entity: its ETag ({} when it has none), undefined when it is not there. */
read: () => Promise<{ etag?: string } | undefined>;
/** The caller's version token: sent as If-Match, nothing read first. */
etag?: string;
/** Without etag: read the entity's ETag right before the write (optimistic concurrency). */
readEtag?: boolean;
/** Whether the entity is there, after a write with nothing to send. Default: read. */
exists?: () => Promise<boolean>;
},
): Promise<ODataKeyedChange>;
interface ODataKeyedChange {
/** The entity was there (with etag: still had it); the write was applied or had nothing to send. */
matched: boolean;
/** The write was sent and applied. */
modified: boolean;
/** After a skipped write with etag: the entity as the read found it (null: not there). */
current?: { etag?: string } | null;
}Writes one entity by key (an update, a replace, a delete) the way both hosts write one, and tells whether it matched; write(etag) sends it with etag as If-Match. With the caller's version token the write goes once: a 412 or a 404 matches nothing, and a write with nothing to send (skipped) matches when the entity still has the token. Without one it is last-write-wins: with readEtag the current ETag is read first and sent (* for an entity that comes without one: the set wants an If-Match), an entity not there matches nothing, and a 412 in between has it read and sent again (retryWhileChanged), a write without readEtag is sent once; a 404 matches nothing, and so does a 412 to the * sent after a read without an ETag when one more read finds the entity gone (found, the service does not take *: ODataServiceError IF_MATCH_REFUSED), and nothing to send matches when the entity is there. Any other failure is thrown. The Moost server's adapter and the browser client map the outcome to moost-db's answers: { matchedCount, modifiedCount }, { deletedCount }, and for an unmatched write with the token the browser's 404 or version mismatch.
import { changeByKey } from "@atscript/odata";
const { matched, modified } = await changeByKey(
(etag) => service.update("OrderSet", key, { Status: "R" }, { etag }),
{
read: async () => {
const found = await service.readOne({ entitySet: "OrderSet", key });
return found && { etag: found.etag };
},
readEtag: true,
},
);dbFailureOf
function dbFailureOf(error: unknown, context?: ODataMessageContext): ODataDbFailure | undefined;
interface ODataDbFailure {
/** The DbError code of @atscript/db the failure is answered with. */
code: ODataDbFailureCode;
/** The status moost-db answers the code with. */
status: 400 | 409 | 429 | 502 | 503 | 504;
message: string;
entries: ODataDbFailureEntry[];
}
type ODataDbFailureCode =
| "INVALID_QUERY"
| "NOT_SUPPORTED"
| "CONFLICT"
| "SERIALIZATION_FAILURE"
| ODataStoreFailureCode;
type ODataStoreFailureCode = "STORE_FAILED" | "STORE_TIMEOUT" | "STORE_THROTTLED";
interface ODataDbFailureEntry {
path: string;
message: string;
/** moost-db's code (UNKNOWN_FIELD, …), the engine's, the service's; else the failure's code. */
code?: string;
/** Values the message names; { retryAfter } (seconds) on a STORE_THROTTLED entry. */
params?: Record<string, unknown>;
}The one mapping of the engine's failures both hosts answer with: @atscript/db-odata throws it as a DbError (toDbError), the browser client as the ClientError a Moost server's answer becomes (toClientError). Both hosts answer such a failure with the same status and entries. The envelope can differ where Moost DB's own controller checks refuse a field before the adapter is asked (its code and wording at the top): branch on the entries' codes. context maps the targets of the service's messages to field paths. undefined for a failure each host answers its own way (the service refused the credentials, could not be reached or read, answered another status): a Moost server as STORE_FAILED or STORE_TIMEOUT (toDbError), the browser as what it saw (toClientError).
| Thrown | code (status) | Entries |
|---|---|---|
ODataQueryError UNSUPPORTED_AGGREGATE, UNSUPPORTED_ON_V2 | NOT_SUPPORTED (400) | one at the error's path |
ODataWriteError of writeRefusal (NOT_INSERTABLE, …) | NOT_SUPPORTED (400) | one at "" |
any other ODataQueryError | INVALID_QUERY (400) | one: UNKNOWN_FIELD or FIELD_NOT_PERMITTED (with params) at the field, UNKNOWN_RELATION at $with (params.relation the dotted name), else the engine's code at the path |
any other ODataWriteError | INVALID_QUERY (400) | one at the payload path, the engine's code (INVALID_VALUE, …) |
ODataValueError | INVALID_QUERY (400) | one at the property |
ODataServiceError PAGE_LIMIT | INVALID_QUERY (400) | one at $limit |
ODataError with hint: "batch-unsupported" (the service has no $batch endpoint: 404, 405, 501) | NOT_SUPPORTED (400) | one at "": never a missing row |
ODataError 412 of a changeset of several requests (changeset.size over 1) | SERIALIZATION_FAILURE (503) | one at "": nothing in the changeset was applied; read the rows again and send the batch again |
ODataError 404, 410 of a changeset of several requests | CONFLICT (409) | as for 400: nothing in the changeset was applied |
ODataError 400 | INVALID_QUERY (400) | the service's messages by field (messageEntries); its leading message at "" with its code when it names no field and no detail repeats it |
ODataError 409 | CONFLICT (409) | as for 400 |
ODataError 412 | SERIALIZATION_FAILURE (503) | one at "", no code: the last attempt of retryWhileChanged met a change too |
ODataError 429 | STORE_THROTTLED (429) | one at "", params.retryAfter (seconds) from the service's Retry-After |
ODataError 504 | STORE_TIMEOUT (504) | one at "" |
ODataError other 5xx | STORE_FAILED (502) | one at "" |
ODataError 501 | NOT_SUPPORTED (400) | as for 400: a definite answer (a method, function or query option the service does not implement) |
An entry without a code of its own takes the failure's (INVALID_QUERY, NOT_SUPPORTED, the STORE_* codes), as Moost DB fills it in. The STORE_* messages are generic: what the service said stays in the error, the cause of the host's. Both hosts answer a 412 to a write with the caller's version token as Moost DB answers a version mismatch, without asking this mapping.
storeFailure
function storeFailure(code: ODataStoreFailureCode, retryAfter?: number): ODataDbFailure;A call the service did not serve, as dbFailureOf answers it: one entry at "" with the code's generic message, and params.retryAfter when a wait is given. toDbError of @atscript/db-odata uses it for the failures only a Moost server answers so (no answer, refused server credentials, an aborted call).
rowsFailure
function rowsFailure(
total: number,
failed: readonly ODataRowFailure[],
created?: readonly { index: number; insertedId: unknown }[],
): { message: string; entries: ODataDbFailureEntry[] };
interface ODataRowFailure {
/** The row's index in the request. */
index: number;
/** The message, code and params a call on the row alone is answered with. */
message: string;
code?: string;
params?: Record<string, unknown>;
/** Its entries, their paths about the row alone. */
entries: readonly ODataDbFailureEntry[];
}The message and entries of a write or an operation on several rows where rows failed, the one rule both hosts answer it by (an array insert, an operation on several rows whose every row failed). In row order: each failed row's entries at that row ([1].Note, [1]; a row whose answer lists none, one entry at [1] with its message, code and params), and for each row created one { path: "[j]", code: "INSERTED", message: "The row at [j] was created", params: { insertedId } }. The message is the first failed row's when none was created, else "k of N rows were created; the row at [i] failed". The status and code are the first failed row's, which the host keeps.
Messages
messageEntries
function messageEntries(
messages: ODataMessages,
context?: ODataMessageContext,
): ODataMessageEntry[];
interface ODataMessages {
message: string;
code?: string;
target?: string;
details: readonly ODataMessage[];
}
interface ODataMessageEntry {
/** Field path, "." between segments; "" for the request as a whole. */
path: string;
message: string;
code?: string;
/** `{ id }`: the key of the row of an operation on several rows the message names. */
params?: Record<string, unknown>;
}
interface ODataMessageContext {
model?: ServiceModel;
/** The entity set the failed call addressed. */
entitySet?: string;
/** Of a failed operation call: its parameters (runParameters); a target naming one is that field. */
parameters?: readonly string[];
}The messages of a failure as entries by field: the one rule both hosts report a service's messages by, on v2 and v4. The leading message becomes an entry only when it has a target; every message with a target becomes an entry at the field path it maps to; a detail without a target becomes an entry at "" unless it repeats the leading message; warnings sent along with an error are left out. A message that names a row of an operation run on several rows (ODataMessage.row) is at that row: [1], [1].Note, with the row's key as params.id (ODataMessage.id). An ODataError is an ODataMessages. dbFailureOf adds the leading message of a 400 or 409 at "", with its code, when it names no field and no detail repeats it.
messagePath
function messagePath(target: string | undefined, context?: ODataMessageContext): string;Maps the target of a service message to a field path of the entity set: CompanyCode, /OrderSet('1')/NetAmount, Items(ItemNo='10')/Quantity and _it/Address/City become CompanyCode, NetAmount, Items.Quantity and Address.City. With the context's parameters (an operation call), a target whose first segment is one of them is that parameter's path first (percent, address.City). A target that names no property, and a pseudo target like /#TRANSIENT#, yield "".
hasMessageTarget
function hasMessageTarget(target: string | undefined): target is string;Whether a target names something: empty targets and pseudo targets such as /#TRANSIENT# count as none.
ODataMessage
interface ODataMessage {
code?: string;
message: string;
/** A property name or a resource path, as the service wrote it. */
target?: string;
/** success, info, warning or error where the service used a known value. */
severity?: string;
additionalTargets?: string[];
longtextUrl?: string;
/** v4 `$batch`: the Content-ID of the changeset request it is about (`@Core.ContentID`). */
contentId?: string;
/** In the error of an operation run on several rows as one changeset: the row it names. */
row?: number;
/** With `row`: the key of that row. */
id?: Record<string, unknown>;
}One message of a service: an error detail, or a note attached to a successful answer. row and id (the index and the key of the row) are set by runOperation on the messages of a refused changeSet run that name a row; messageEntries reports them at that row, the key as params.id.
Annotations
ODATA_ANNOTATIONS
const ODATA_ANNOTATIONS: {
"odata.valueHelpService": ODataAnnotationDef; // on an interface
};The @odata.* annotations the generated models carry: protocol facts no existing Atscript annotation holds. The plugin declares them (see odataAnnotations).
| Annotation | On | Holds |
|---|---|---|
@odata.valueHelpService '…' | interface | The entity set is in a value-help service of the service (v4 Common.ValueListReferences), named by its root without matrix parameters. |
Everything else is an annotation of Atscript DB or Atscript UI: the entity set is the interface's @db.table, and the service's name its @db.space (the space a Moost server registers with provideDbSpace(space, name)).
The operation types (<Name>Params) carry none of these: they are plain Atscript interfaces (@meta.label, @expect.*, @db.column.precision, ?); an operation's facts stay in the service model.
ODataAnnotationDef
interface ODataAnnotationDef extends AnnotationDef {
description: string;
/** Atscript source lines showing the annotation in use. */
example: string[];
nodeType: ("interface" | "prop" | "type")[];
}Building blocks
The functions below are what the service engine and the two hosts are made of. Reach for them only to write a host of your own or to inspect what would be sent; @atscript/odata-client and @atscript/db-odata already use them. Each takes the model and the ProtocolContext (service.context) explicitly and does no I/O unless noted.
Read planning
function readSpecFromUniquery(
entitySet: string,
query: Uniquery | undefined,
options?: ReadSpecOptions,
): ReadSpec;
function planRead(
spec: ReadSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: ReadRequestOptions,
): ReadPlan;
function buildReadRequest(
spec: ReadSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: ReadRequestOptions,
): ODataRequest;
function buildCountRequest(
spec: ReadSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: ReadRequestOptions,
): ODataRequest;
interface ReadSpecOptions {
model?: ServiceModel; // needed for an exclusion $select
ignoreControls?: string[]; // controls the host handles itself
}
interface ReadPlan {
request: ODataRequest;
target: ReadTarget;
}
interface ReadTarget {
entityType: string;
entitySet: string;
single: boolean;
}| Export | Does |
|---|---|
readSpecFromUniquery | Converts a Uniquery (filter, $select, $sort, $skip, $limit, $count, $search, $with) into a ReadSpec; refuses grouping controls with UNSUPPORTED_CONTROL. |
planRead | The request of a read and what its answer holds; throws ODataQueryError. |
buildReadRequest | The request of planRead alone. |
buildCountRequest | The /$count request of a read. |
Aggregation planning
function aggregateSpecFromUniquery(
entitySet: string,
query: Uniquery | undefined,
options?: { ignoreControls?: readonly string[] },
): AggregateSpec;
function planAggregate(
spec: AggregateSpec,
model: ServiceModel,
ctx: ProtocolContext,
): AggregatePlan;
function readAggregateRow(
item: Record<string, unknown>,
plan: AggregatePlan,
model: ServiceModel,
ctx: ProtocolContext,
): Record<string, unknown>;
function emptyAggregateRow(plan: AggregatePlan): Record<string, unknown>;
interface AggregatePlan {
request?: ODataRequest; // absent when nothing needs asking
empty?: "rows" | "groups";
target: { entityType: string; entitySet: string };
groupBy: string[];
columns: AggregateColumn[];
}
interface AggregateColumn {
alias: string;
odata: string;
type: CodecType;
}| Export | Does |
|---|---|
aggregateSpecFromUniquery | Converts db-client's aggregate() query into an AggregateSpec. |
planAggregate | The $apply request and how its rows decode; refuses with UNSUPPORTED_AGGREGATE. |
readAggregateRow | Decodes one row of the answer under the caller's aliases. |
emptyAggregateRow | The one row an ungrouped read answers over no matching row (counts 0, the rest null). |
Write planning
function planCreate(
spec: CreateSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): WritePlan;
function planUpdate(
spec: UpdateSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): WritePlan;
function planReplace(
spec: UpdateSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): WritePlan;
function planDelete(
spec: DeleteSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): WritePlan;
function buildCreateRequest(
spec: CreateSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): ODataRequest;
function buildUpdateRequest(
spec: UpdateSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): ODataRequest;
function buildReplaceRequest(
spec: UpdateSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): ODataRequest;
function buildDeleteRequest(
spec: DeleteSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): ODataRequest;
function readWriteResponse(
response: ODataResponse,
target: WriteTarget,
model: ServiceModel,
ctx: ProtocolContext,
): WriteResult;
function parseEntityKey(
url: string,
entityType: string,
model: ServiceModel,
ctx: ProtocolContext,
): Record<string, unknown> | undefined;
interface CreateSpec {
entitySet: string;
data: Record<string, unknown>;
}
interface UpdateSpec {
entitySet: string;
key: Record<string, unknown>;
data: Record<string, unknown>;
}
type DeleteSpec = Omit<UpdateSpec, "data">;
interface WriteTarget {
entityType: string;
entitySet: string;
}
interface WritePlan {
request: ODataRequest;
target: WriteTarget;
dropped: string[];
nothingToSend?: true;
}| Export | Does |
|---|---|
planCreate, buildCreateRequest | POST of an entity; related entities in the payload are created with it (deep insert). |
planUpdate, buildUpdateRequest | MERGE (v2) or PATCH (v4) of the given properties. |
planReplace, buildReplaceRequest | PUT of the whole entity. |
planDelete, buildDeleteRequest | DELETE of one entity. |
readWriteResponse | Reads the answer of a create, update or replace: the entity, its ETag, its key. |
parseEntityKey | Reads a key from a Location / OData-EntityId URL. |
The planners drop what may not be written and list it in dropped; they throw ODataWriteError when the model refuses the write (writeRefusal). On v4 an entity of a type that takes part in inheritance (a base type, or a type derived from it in the model) carries "@odata.type": "#Namespace.Type" first, the related entities of a deep insert too; nothingToSend does not count it.
Operations
function planOperation(
spec: OperationSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): OperationPlan;
function buildOperationRequest(
spec: OperationSpec,
model: ServiceModel,
ctx: ProtocolContext,
options?: WriteRequestOptions,
): ODataRequest;
function readOperationResponse(
response: ODataResponse,
operation: OperationModel,
model: ServiceModel,
ctx: ProtocolContext,
): OperationResult;
interface OperationPlan {
request: ODataRequest;
operation: OperationModel;
}Plan and read the call of a v2 function import or a v4 function or action (ODataService.call uses them). runOperation is the typed, validated runner over the operation types.
- A v2 function import is called at the service root under every dialect. With
bound, the key of the entity fills the parameters of the same names the call does not give. - A parameter name the operation does not declare: on v2 it is sent after the declared ones, untyped (a number or a boolean bare, a string quoted,
null); any other value is refused withINVALID_VALUE, and a name starting with$orsap-(a query option of the service) withUNKNOWN_PARAMETER. On v4 it is refused withUNKNOWN_PARAMETER. - A parameter that is neither nullable nor optional (
ParameterModel.optional, fromCore.OptionalParameter) is required: leaving it out is refused withMISSING_PARAMETER. readOperationResponsethrowsODataPayloadErrorfor an answer that does not fit the declared result: an entity or a collection of entities that is none, and on v4 a primitive value or a collection without its{ "value": … }envelope (control information alone is no value). A v4 null result,@odata.null: true(@nullin 4.01) as services built on ODataLib send it, isnull(an entity result none). The Moost server answers it502STORE_FAILED, the browser client aTransportError, as any payload that is no OData.
Codecs
function formatLiteral(
value: unknown,
type: CodecType,
ctx: ProtocolContext,
model?: ServiceModel,
): string;
function quoteString(text: string): string;
function formatKey(
entityType: string | EntityTypeModel,
key: Record<string, unknown>,
model: ServiceModel,
ctx: ProtocolContext,
): string;
function formatEntityPath(
entitySet: string,
entityType: string | EntityTypeModel,
key: Record<string, unknown>,
model: ServiceModel,
ctx: ProtocolContext,
): string;
function encodePathSegment(segment: string): string;
function keyProperties(entityType: string | EntityTypeModel, model: ServiceModel): PropertyModel[];
function decodeValue(
wire: unknown,
type: CodecType,
ctx: ProtocolContext,
model?: ServiceModel,
): unknown;
function encodeValue(
value: unknown,
type: CodecType,
ctx: ProtocolContext,
model?: ServiceModel,
): unknown;
function decodeEntity(
wire: unknown,
entityTypeName: string,
model: ServiceModel,
ctx: ProtocolContext,
): DecodedEntity;
function encodeEntity(
data: Record<string, unknown>,
entityTypeName: string,
model: ServiceModel,
ctx: ProtocolContext,
): Record<string, unknown>;
function readCollection(body: unknown, ctx: ProtocolContext): CollectionPayload;
function readEntity(body: unknown, ctx: ProtocolContext): Record<string, unknown> | undefined;
function readCount(body: unknown, ctx?: ProtocolContext): number;
function structuredMembers(
name: string,
kind: "entity" | "complex",
model: ServiceModel,
): StructuredMembers | undefined;
type CodecType = TypedElement & { dateOnly?: boolean };
interface DecodedEntity {
data: Record<string, unknown>;
etag?: string;
counts?: Record<string, number>;
}
interface CollectionPayload {
items: Record<string, unknown>[];
count?: number;
nextLink?: string;
}
interface StructuredMembers {
name: string;
kind: "entity" | "complex";
properties: Record<string, PropertyModel>;
navigations: Record<string, NavigationModel>;
key: string[];
}| Export | Does |
|---|---|
formatLiteral, quoteString | A value as a version-aware OData literal (v2 guid'…', datetime'…'; v4 bare). |
formatKey, formatEntityPath | A key predicate (K1=v1,K2=v2), and EntitySet(…) ready for a request path. |
encodePathSegment | Percent-encodes one path segment, keeping key predicate punctuation readable. |
keyProperties, structuredMembers | Key properties and the members of a type with its base types folded in. |
decodeValue, encodeValue | One value between the wire and its Atscript-side form. |
decodeEntity, encodeEntity | One entity, with control information stripped and expansions unwrapped. |
readCollection, readEntity, readCount | The envelopes of v2 and v4 responses. |
Transport
function createTransport(options: ODataTransportOptions): ODataTransport;
function parseErrorBody(body: unknown, contentType?: string): ParsedErrorBody;
function parseSapMessages(headers: Record<string, string>): ODataMessage[] | undefined;
function encodeQueryValue(value: string): string;
function encodeQueryName(name: string): string;
function headersKey(headers: Record<string, string> | undefined): string;
function withLocale<I extends { headers?: Record<string, string> }>(
init: I,
locale: string | undefined,
): I;
interface ODataTransport {
readonly root: string;
readonly version: ODataVersion | undefined;
readonly dialect: ODataDialect;
readonly session?: ODataSession;
readonly csrf?: boolean;
send(request: ODataRequest, init?: ODataSendInit): Promise<ODataResponse>;
fetchMetadata(init?: ODataSendInit, language?: string): Promise<string>;
url(request: ODataRequest): string;
sendBatch(items: ODataBatchItem[], init?: ODataSendInit): Promise<ODataBatchOutcome[][]>;
}
interface ODataTransportOptions {
baseUrl: string;
version?: ODataVersion;
dialect: ODataDialect;
// fetch, headers, credentials, csrf, session, query, merge, batch: see ODataServiceTransportOptions
}
type ODataBatchItem = { request: ODataRequest } | { changeset: ODataRequest[] };
type ODataBatchOutcome = { ok: true; response: ODataResponse } | { ok: false; error: ODataError };
const DEFAULT_BATCH_PARTS = 100;
interface ODataRequest {
method: "GET" | "POST" | "PUT" | "PATCH" | "MERGE" | "DELETE" | "HEAD";
path: string; // relative to the service root, percent-encoded
query?: [name: string, value: string][];
headers?: Record<string, string>;
body?: unknown;
}
interface ODataResponse {
status: number;
headers: Record<string, string>;
body: unknown;
messages?: ODataMessage[];
}
interface ParsedErrorBody {
message?: string;
code?: string;
target?: string;
severity?: string;
details: ODataMessage[];
}| Export | Does |
|---|---|
createTransport | The HTTP transport of one service: CSRF fetch and one retry, cookies in the call's session, error parsing into ODataError. The engine creates one for you. |
parseErrorBody | Reads an error body of any shape: OData v2 JSON and XML, v4 JSON, other JSON, HTML, text. |
parseSapMessages | Reads the sap-message (v2) or sap-messages (v4) response header. |
encodeQueryValue, encodeQueryName | Percent-encode a raw query option value or name. |
headersKey | The headers of a call as one comparable text (names in lower case, sorted): calls with the same key may share one $batch request, which carries one set. |
withLocale | init with the locale as Accept-Language, unless its headers name one (they win) or there is none: how both hosts send the locale. |
fetchMetadata reads $metadata and resolves with the XML text, sent without version headers. With a language it asks for the document in it, as the query option sap-language (over one of the query option) and as Accept-Language (over one of the headers). It rejects with ODataError unexpected-content for an answer that is not XML.
sendBatch sends requests as one OData $batch and resolves one array of outcomes per item, in order: each the response send would resolve with, or the ODataError it would reject with, judged by the same rules (statuses, sap-message, ETags, 412). A changeset item is applied by the service all or nothing. service.batch() is the typed API over it, which auto-batching and the browser client's createBatch() send through.
const transport = createTransport({ baseUrl, version: "v2", dialect: resolveDialect("sap") });
const [[page], [release, confirm]] = await transport.sendBatch(
[
{ request: { method: "GET", path: "Orders", query: [["$top", "20"]] } },
{
changeset: [
{ method: "MERGE", path: "Orders('1')", body: { Status: "R" } },
{ method: "POST", path: "ConfirmOrder", query: [["OrderID", "'1'"]] },
],
},
],
{ session },
);
if (!release.ok) console.log(release.error.message, release.error.changeset); // { size: 2 }- The body is multipart/mixed on v2 and v4. The parts' request lines are relative to the service root and carry the
queryoption; their headers are what a single call sends for itself (Accept,If-Match, a body'sContent-TypeandContent-Lengthin UTF-8 bytes) plus the call'sAccept-Language. Credentials, cookies and the CSRF token go on the$batchrequest only; anAccept,Content-TypeorPreferin the call's headers does not reach it, the$batchrequest sets its own. - The
$batchrequest counts as a write: the CSRF token is fetched and, on403+Required, fetched again and the batch sent once more. - v4 gives every changeset request a Content-ID and matches the answers by it; it sends
Prefer: odata.continue-on-error, and requests a service still leaves unanswered in a complete answer are sent again in a further$batch. v2 sends no Content-ID and matches by position. The Content-IDs are the transport's, numbered per$batch: a request cannot refer to another one by Content-ID ($1). - An answer that ends early on v2, or is cut off before its end, sends nothing again: each request it leaves without a part fails with
unexpected-content, since it may have run. - A changeset the service refused as a whole gives its error to every request in it, with
changesetset; on v4 each request'sdetailsare the messages that name its Content-ID, and those that name none. - More than
batch.maxPartsrequests go out as several batches, one after the other; a changeset is never split. - It rejects when the
$batchrequest fails as a whole before any request has an answer: the network,401, a malformed body, a login page, a token still refused after the retry;hint: "batch-unsupported"for404,405and501. A further batch of the samesendBatchcall that fails so gives its error to every item not answered yet, sent or not; a failure that is noODataError(aheadershook that threw) is wrapped in one, kindnetwork, with the original ascause.
ODataTransportOptions takes the options listed at ODataServiceTransportOptions, with dialect as an ODataDialect object and an optional version.
Annotation and emitter internals
const ANNOTATIONS: { [key: string]: AnnotationDef }; // every annotation a plan may hold
type AnnotationKey = keyof typeof ANNOTATIONS;
function annotationDef(key: string): AnnotationDef;
function annotationValue(
annotation: PlanAnnotation,
resolveRef?: (name: string) => unknown,
): unknown;
function annotationsMetadata(
annotations: PlanAnnotation[],
resolveRef?: (name: string) => unknown,
): Map<string, unknown>;
const PLAN_PRIMITIVES: Record<PlanPrimitive, PlanPrimitiveDef>;
interface AnnotationDef {
args: readonly AnnotationArgDef[];
shape: "flag" | "value" | "object";
multiple?: boolean;
append?: boolean;
passedWhenReferred: boolean;
}
interface AnnotationArgDef {
name: string;
type: PlanArg["type"];
optional?: boolean;
description?: string;
userText?: boolean;
}
interface PlanPrimitiveDef {
designType: "string" | "number" | "boolean" | "decimal";
tags: string[];
annotations: PlanAnnotation[];
}How the runtime builder stores annotations and primitives the way the Atscript compiler does. ANNOTATIONS restates the specs of every annotation a plan may emit (@odata.*, and those of Atscript core, @atscript/db and @atscript/ui it uses).
Model and plan types
The service model is plain JSON: no classes, maps, functions or cycles. It can be snapshot-tested, cached and shipped to a browser in place of the XML. Names are qualified (<Namespace>.<Name>) with schema aliases resolved.
| Type | Holds |
|---|---|
ServiceModel | One service: version, vendor ("sap" for Gateway and RAP), entity, complex and enum types, type definitions, entity sets, singletons, operations, references, annotations, valueHelpServices, and in a model module build (ServiceModelBuild). |
ValueHelpServiceModel | A value-help service: its path relative to the service root and its own model. |
DetachedAnnotations | Value lists and annotations whose target is not an element of this model. |
SchemaInfo | A schema namespace and its alias. |
ReferenceModel | An edmx:Reference and its includes. |
EdmPrimitive | Edm primitive type names without Edm.. |
TypeRef | A primitive by name, or a complex, enum, type definition or entity type by qualified name. |
TypeFacets | maxLength, precision, scale, unicode, srid. |
TypedElement | A TypeRef with facets, collection and nullable. |
EntityTypeModel | Key, properties, navigations, base type, label, parameters flag. |
ComplexTypeModel | Properties and navigations of a complex type. |
EnumTypeModel | Members with values and labels. |
TypeDefinitionModel | A v4 type definition over a primitive. |
PropertyModel | One property with label, heading, quick info, computed / immutable / update-only marks, unit or currency, text, semantics, field control, value lists. |
PropertySemantics | currency-code, unit-of-measure, email, tel, url, and calendar semantics. |
TextArrangement | TextFirst, TextLast, TextOnly, TextSeparate. |
FilterRestriction | single-value, multi-value, interval. |
FieldControl | A static field-control value, or the path of the property holding it. |
NavigationModel | Target, cardinality, referential constraints, partner, containment. |
EntitySetModel | Entity type, navigation bindings, capabilities, label. |
SingletonModel | A v4 singleton. |
EntitySetCapabilities | Insert, update, delete, search (searchable, and searchDeclared where the metadata states it rather than the version's default: what search: false keeps), count, paging, per-property filter and sort, filter restrictions, $apply, optimistic concurrency, draft. |
OperationModel | A function or action, bound or unbound, with parameters and return type; its label (also from a UI.DataFieldForAction), available (a path of the bound entity, or false), grouping (isolated or changeSet) and draft (a draft lifecycle operation). |
ParameterModel | One operation parameter, with its label, optional (Core.OptionalParameter) and dateOnly (v2 sap:display-format="Date" on an Edm.DateTime). |
ValueListModel | One value list: collection path, parameters, search support, label, value-help service. |
ValueListParameter | In, Out, InOut, DisplayOnly or Constant. |
AnnotationMap | Annotations not folded into a field, keyed by term. |
AnnotationValue | An annotation value in CSDL JSON shape. |
ServiceModelBuild
interface ServiceModel {
// … the members above
/** What the generator built this model from; absent on a model the parser gives. */
build?: ServiceModelBuild;
}
interface ServiceModelBuild {
/** The name the types were generated with (@db.space). */
service: string;
/** The entity sets the generation was limited to; absent: all of them. */
entitySets?: string[];
/** The operations the generation left out (the plugin's `operations`); absent: none named. */
operations?: { exclude: string[] };
/** The language the documents were saved in (the plugin's `language`). */
language?: string;
/** metadataDigest of the saved $metadata. */
metadata: string;
/** For every value-help reference, the digest of the document the generator read; null: none. */
valueHelps: Record<string, string | null>;
}The build record the plugin writes into the model of a model module. The app never writes it. A live source compares the live documents with these digests (the fast path), plans the live model with the same service, entitySets and operations, and reads the metadata in language.
The plan types describe what the generator emits (see planService):
| Type | Holds |
|---|---|
ServicePlan | service, version, aliases, interfaces, operations and skipped. |
PlanOperation | A selected operation: its <Name>Params type, the operation name the engine calls, localName, binding, level (rows / table), entitySets, keyParameters (v2 rows: filled by the row's key), available (rows: the availability path a row is checked by, a path to a Boolean of the entity, . between segments), result. Its other facts stay on its OperationModel. |
PlanInterface | One interface: name, extends, type-level annotations, own properties, source. |
PlanAlias | One named type alias (an enumeration). |
PlanProp | One property: name, optional flag, type, annotations. |
PlanType | A primitive, a reference (with a path for a chain reference), an array or a literal union. |
PlanPrimitive | The Atscript primitives a plan uses (string, string.uuid, decimal, number.int.int32, …). |
PlanAnnotation | One annotation occurrence: key and positional arguments. |
PlanArg | One argument: string, number, boolean, reference or value-help filter. |
PlanCondition | One condition of a value-help filter: equal to a literal or to a host field. |
PlanSource | Where a declaration comes from in the model: an entity type, entity set, complex or enum type, or an operation. |
PlanOptions | service, entitySets and operations: see buildServiceTypes. |
SkippedItem | Something the plan does not express: kind, where, what, why. The trailer of a generated .as file lists these. |
SkippedKind | singleton, type, property, navigation, valueList, annotation, operation. |