@atscript/odata-client
Complete export reference for @atscript/odata-client. See The browser client for the narrative.
pnpm add @atscript/odata-client @atscript/db-client @atscript/db @atscript/core @atscript/typescript @uniqu/coreOne entry point (.), browser and Node. The client stands in for the Client of @atscript/db-client: Atscript UI tables, filters, forms and value helps work against an OData v2 or v4 service with no Atscript server in between.
Classes
ODataClient
const ODataClient: ODataClientConstructor;
interface ODataClientConstructor {
new <
T extends AtscriptClientShape = AtscriptClientShape,
D extends object = Record<never, never>,
>(
options: ODataClientOptions,
): ODataClient<T, D>;
readonly prototype: ODataClient;
}
interface ODataClient<
T extends AtscriptClientShape = AtscriptClientShape,
D extends object = Record<never, never>,
> extends ClientLike<T, D, ODataClientCallOptions> {
/** The engine the client reads through. Known once the client is connected. */
readonly service: ODataService;
readonly entitySet: string;
/** The type of the entity set. Known once the client is connected. */
readonly type: TAtscriptAnnotatedType;
/** The URL atscript-ui knows the entity set by. */
readonly url: string;
}A client for one entity set. It is a ClientLike<T, D, ODataClientCallOptions> of @atscript/db-client (every public member of Client, its calls taking ODataClientCallOptions), not a subclass: instanceof Client is false, and atscript-ui's client factories take it as it is. You rarely construct one yourself: createODataClientFactory creates one per URL.
A client of a live service connects before its first call (see ODataClientOptions connect). Until then service and type throw an Error; every method works and connects first.
Client member | ODataClient |
|---|---|
meta(), metaEtag(), invalidateMeta(), getValidator() | Built from the service model and the entity set's type (buildMeta) |
query(), count(), pages(), one() | OData reads; one() resolves null for a missing entity |
insert(), update(), replace(), remove() | OData writes where the entity set allows them; see Writes and concurrency |
aggregate() | One OData v4 $apply request; see Aggregation |
geoSearch(), geoPages(), actionOnQuery(), countActionTarget() | Reject with ClientError 400 NOT_SUPPORTED, no call made |
action(), getActionForm(), availableActions(), $actions on reads | The operations bound to the set's type, with operations (see below) |
getActionFormTexts() | undefined: the forms carry their labels |
Actions. With the service's operations (the factory passes them), the operations of the live service bound to the set's type are the client's db actions, as a Moost server's generated base declares them (see Operations in the browser):
meta().actions: one per operation, named by its key inops(the local name),levelrowsortable,processor: "backend",labelthe@meta.labelof its live<Name>Paramstype (else the name),inputFormwhere that type has properties,value<url>/actions/<name>(nothing is fetched from it).getActionForm(name): the live<Name>Paramstype;nullfor an action without parameters or not listed.action(name, ids?, input?):inputvalidated against the form (ClientValidationError); on rows (ids, an array of key objects) the rows' tokens read in one collection read where the call writes on a set with a version token, unless its reads must filter outside the key (a row not found:ClientError404; one id and one row read is that id's row, whatever literal form the id was written in, several are matched by the keys the codec writes); thenrunOperationwith each token asIf-Match(a412on it: that row'sVersionMismatchError), several rows as one$batchby the live operation's grouping (isolatedwhere the$metadatanames none; one call per row with the registration'sbatch: false, achangeSetrun then refusedClientError400NOT_SUPPORTED). On rows it answersODataRowsAnswer, as a Moost server's generated base does: every row of several failed is the first row's error with every row's entries at[i], a refusedchangeSetrun its one error (see Several rows), one row's failure its own error;skippedis always empty. On the collection:{ value, message?, messages?, details? }. An action not listed:ActionNotFoundError;idsthat are no array on rows:TypeError.availableActions(id):{ actions }, the row actions whose availability path is notfalseon the row (one read of the key and the paths);{ actions: [] }for a row that does not exist.$actions: truein the controls ofquery(),pages()orone(): each row gets$actions, those row actions. A$selectis widened by the paths it lacks, which are taken out of the rows again. Rows are left alone when the set has no row actions.
The availability is a hint: no call is refused by it. Without operations the client declares no actions, and action() throws ActionNotFoundError, as Client does for such a backend.
Errors are db-client's classes: ClientError, ClientValidationError, VersionMismatchError, TransportError. See Errors.
The batch call option. The options of query, count, pages, aggregate, one, insert, update, replace and remove are ODataClientCallOptions, which take batch (see Batching):
batch | The call |
|---|---|
| absent | is auto-batched with the calls of the same pass, where its service's engine auto-batches (a live registration's does, unless it says batch: false). |
false | goes out alone, its pre-reads and retries too. |
an ODataClientBatch | queues its request in that batch: a read as a part of its own, a write in a changeset of its own. A pre-read goes out before it, alone; what follows its answer goes out after the batch, alone. |
an ODataClientChangeset | a write queues its request in that changeset; a read is refused (TypeError). |
Given a batch or changeset, an array insert, update or replace, a client of another service root (a value-help service, another registration) and a call whose session or headers differ from the batch's first call throw TypeError; a batch that has gone out throws Error. Only an ODataClient reads it: a client of another backend (the factory's fallback) ignores it.
Functions
createODataClientFactory
function createODataClientFactory(options: ODataClientFactoryOptions): ODataClientFactory;Creates the client factory atscript-ui routes through. A URL <prefix>/<service>/<EntitySet> gets an ODataClient for that entity set; a URL <prefix>/<service>/<value-help service>/<EntitySet> (segments URI-encoded) one for a set of a value-help service; every other URL goes to fallback.
A live service (LiveServiceRegistration) is read on the first call of any of its clients, or by connect(): its $metadata and value-help documents, in the language the models were saved in, one read for all its clients. Its generated module's classes are the live declarations from then on (see createODataSource).
- Before the read, a URL of the service gets a client that connects first.
- An entity set the live service lacks answers every call with
ClientError404NOT_FOUND. - A failed read is not kept: the next call reads again, so a user who signs in again needs no reload. Its error is what a data call throws for the same failure (
ClientErrorwith the status, 401UNEXPECTED_CONTENTfor a login page,TransportErrorfor no answer or an answer that is no$metadata). db.http.path. Once a service is connected (a fixed one: at once), the factory writes each entity set's URL into its type asdb.http.path. That is how atscript-ui finds the target of a foreign key or of a@ui.valueHelp. A type object carries one URL: registering it with a second factory under another prefix or name re-points it.
Throws for a service registered twice, and for fixed types that do not belong to the service they are registered with.
// src/main.ts
import { createODataClientFactory } from "@atscript/odata-client";
import { setDefaultClientFactory } from "@atscript/ui";
import { createApp } from "vue";
import App from "./App.vue";
import * as sales from "./odata/sales.as";
import { model } from "./odata/sales.model.gen";
const odata = createODataClientFactory({
services: [
{
baseUrl: "/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
query: { "sap-client": "100" },
model,
types: sales,
},
],
});
setDefaultClientFactory(odata);
odata.connect().then(() => createApp(App).mount("#app"), showStartError);
// <AsTableRoot url="/odata/sales/OrderSet" /> now reads ODatashowStartError stands for your own code. See Browser client.
buildMeta
function buildMeta(options: BuildMetaOptions): MetaResponse;Builds the /meta answer of an entity set, as @atscript/moost-db answers GET /meta for a table: the type serialized by serializeMetaType of @atscript/db/meta (the code moost-db serves /meta with, so the two are byte-identical for the same type), the fields with their sort and filter capabilities and filterOps, the key, the relations the service expands, versionColumn, the reads and the writes the set allows in crud, the aggregate functions, and the actions given. ODataClient.meta() answers this, with its actions. Throws when the model has no such entity set or the type is not an interface.
toClientError
function toClientError(error: unknown, context?: ODataClientErrorContext): unknown;Turns what the OData engine throws into what @atscript/db-client throws, so one instanceof ClientError / instanceof TransportError branch handles both backends. An error that is already db-client's, or one this package does not know, comes back unchanged.
A failure a Moost server answers with a DbError (dbFailureOf of @atscript/odata, the one mapping both hosts use) becomes the ClientError the Moost server's answer becomes: the status Moost DB gives the code, and its body (message, statusCode, code, errors). Both hosts give the same status and entries; branch on the entries' codes (on the server Moost DB's own checks may refuse a field first, with its code and wording at the top).
| Thrown by the engine | Result |
|---|---|
ODataQueryError UNSUPPORTED_AGGREGATE, UNSUPPORTED_ON_V2 | ClientError 400 NOT_SUPPORTED |
ODataWriteError of writeRefusal (NOT_INSERTABLE, …) | ClientError 400 NOT_SUPPORTED |
ODataQueryError (other) | ClientError 400 INVALID_QUERY; UNKNOWN_FIELD, FIELD_NOT_PERMITTED, UNKNOWN_RELATION at $with, else the engine's code on the entry |
ODataWriteError (other) | ClientError 400 INVALID_QUERY; the engine's code on the entry, payload path |
ODataValueError | ClientError 400 INVALID_QUERY, the property |
ODataServiceError PAGE_LIMIT | ClientError 400 INVALID_QUERY on $limit |
ODataError 400 | ClientError 400 INVALID_QUERY, the service's messages by field |
ODataError 409 | ClientError 409 CONFLICT, the service's messages by field |
ODataError 412 (the last attempt of a last-write-wins write) | ClientError 503 SERIALIZATION_FAILURE |
ODataError 429 | ClientError 429 STORE_THROTTLED, the service's Retry-After as params.retryAfter (seconds) on the entry |
ODataError 504 | ClientError 504 STORE_TIMEOUT |
ODataError 501 | ClientError 400 NOT_SUPPORTED, the service's messages by field |
ODataError 5xx (other) | ClientError 502 STORE_FAILED |
ODataError http / csrf (other statuses) | ClientError with the HTTP status, the service's code and messages by field (401, 403: the user's own session) |
ODataError unexpected-content, an HTML page or a redirect | ClientError 401 UNEXPECTED_CONTENT |
ODataError network / aborted, an unreadable 2xx | TransportError |
ValidatorError (an operation's parameters, runOperation) | ClientValidationError (400): the validator's entries, code and params kept |
messagePath
function messagePath(target: string | undefined, context?: ODataClientErrorContext): string;Maps the target of a service message to a field path of the entity set: messagePath of @atscript/odata, with this package's context type.
unsupportedOperation
function unsupportedOperation(operation: string, entitySet: string): ClientError;The error of an operation the client does not implement: ClientError 400 NOT_SUPPORTED. Useful when you wrap the client and want to refuse the same way.
Constants
DEFAULT_ODATA_PREFIX
const DEFAULT_ODATA_PREFIX = "/odata";The URL prefix OData entity sets are addressed under unless the factory is given another.
DEFAULT_QUERY_LIMIT
const DEFAULT_QUERY_LIMIT = 1000;Rows query() returns when the query sets no $limit, as moost-db's /query does.
Types
ODataClientFactoryOptions
interface ODataClientFactoryOptions {
services: ClientServiceRegistration[];
/** Default DEFAULT_ODATA_PREFIX. A trailing slash is ignored. */
prefix?: string;
/** Client of every other URL. Default: a plain db-client Client. */
fallback?: (url: string, options?: ODataClientFactoryCallOptions) => ClientLike;
/** Send atscript-ui's locale as Accept-Language (default), or leave the language to the service. */
locale?: "accept-language" | "ignore";
/** For every client: rows query() returns without $limit. Default 1000; 0 reads everything. */
queryLimit?: number;
/** For every client: session, headers and read options of every OData call. */
call?: ODataCallInit;
}One application can mix OData and Atscript DB backends: the fallback serves every URL outside the prefix.
ClientServiceRegistration
type ClientServiceRegistration = LiveServiceRegistration | FixedServiceRegistration;One OData service a client factory serves. An application registers its services live.
LiveServiceRegistration
type LiveServiceRegistration = Omit<ODataSourceOptions, "onDrift" | "verdicts" | "batch"> & {
/** $batch settings: maxParts (default 100), auto (default true); false: no $batch unless asked for. */
batch?: false | ODataSourceOptions["batch"];
};A service read live: ODataSourceOptions of @atscript/odata, without onDrift and verdicts; its engine auto-batches by default (batch.auto of ODataServiceTransportOptions). The browser runs on whatever the live service has: it computes no drift report and no operation verdicts and logs nothing about a change, and code that names a property or an operation the live service dropped fails at runtime (see In the browser).
| Option | Meaning |
|---|---|
baseUrl, query, headers, credentials, dialect, merge, session, fetch | The transport options (ODataServiceTransportOptions). |
model | The model export of the generated *.model.gen.ts. |
types | The generated .as module, whole: import * as sales from "./odata/sales.as". |
name | The URL segment of the service. Default: the name the models were generated with. |
copies | The app's annotate X as Y copies that annotate properties (see Your annotate blocks). |
language, entitySets | Only for a registration without model: the language to read the $metadata in (the models name theirs; data calls and operations carry the caller's locale instead), and the entity sets to build types for. |
batch | false: no auto-batching, every call goes out alone unless it is given a batch of createBatch, an action on several rows goes one call per row (a changeSet run refused), an array insert one create per row: the registration's services are created with the engine's batch: false. { maxParts }: the most requests one $batch carries. See Batching. |
search | false: an entity set is searchable only where the metadata declares it, not by the OData v4 default (search): for a v4 service that refuses $search. |
A session given here is the session of the service's clients. Without model and types the registration is runtime-only: the types are built from the live document, and the app cannot import them (see Without generated models).
// Runtime-only: no build step, no TypeScript types.
const odata = createODataClientFactory({
services: [
{
name: "sales",
baseUrl: "/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
entitySets: ["OrderSet", "CustomerSet"],
},
],
});
const { sales } = await odata.connect();
// sales.plan.skipped lists what the types do not expressFixedServiceRegistration
interface FixedServiceRegistration {
/** The name in URLs; use the name the types were generated with (@db.space). */
name: string;
service: ODataService;
/** The generated module (import * as sales), the types of buildServiceTypes, or its result. */
types: Record<string, unknown>;
}A service whose engine and types are at hand, read from no $metadata: for tests and tools. service comes from createODataService, and batches as it was created (batch: { auto: true } to auto-batch). Entries of types that are not entity set types (@db.table) serve no URL; the operation types (<Name>Params) among them are the forms of the service's operations. A type of an entity set the model does not have is refused.
ODataClientFactory
interface ODataClientFactory {
<T extends AtscriptClientShape = AtscriptClientShape>(
url: string,
options?: ODataClientFactoryCallOptions,
): ClientLike<T, Record<never, never>, ODataClientCallOptions>;
/** The client of the entity set a generated type is of, typed by it. */
client<T extends TAtscriptAnnotatedType & AtscriptClientShape>(
type: T,
options?: ODataClientFactoryCallOptions,
): ODataClient<T>;
/** The URL of the entity set a generated type is of. */
urlOf(type: TAtscriptAnnotatedType): string;
/** The URL of an entity set, or of a set of one of its value-help services. */
urlOf(service: string, entitySet: string, valueHelpService?: string): string | undefined;
/** The service and entity set a URL addresses; undefined for a URL of the fallback. */
resolve(
url: string,
): { service: string; entitySet: string; valueHelpService?: string } | undefined;
/** Connects the live services (all, or the one named) now. */
connect(service?: string): Promise<Record<string, LiveServiceConnection>>;
/** Calls an operation by its handle of `ops`, typed by it alone. */
call<P, R, K>(
operation: ODataOperationRef<P, R, K>,
// the input is required when the operation has a required parameter or is called on rows
...input: {} extends ODataTypedCallInput<P, K>
? [input?: ODataTypedCallInput<P, K>, opts?: ODataOperationCallOptions]
: [input: ODataTypedCallInput<P, K>, opts?: ODataOperationCallOptions]
): Promise<ODataCallAnswer<R>>;
/** Calls an operation by its name, untyped: one only the live service has. */
callByName(
operation: string | ODataOperationName,
input?: ODataUntypedCallInput,
opts?: ODataOperationCallOptions,
): Promise<ODataCallAnswer>;
/** A new batch of a registered service (the name may be left out with one service). */
createBatch(service?: string): ODataClientBatch;
}Pass it to setDefaultClientFactory of @atscript/ui, or to one table's clientFactory. The clients it returns take ODataClientCallOptions: an entity set's ODataClient reads batch, a fallback client ignores it.
connect(service?)reads the live services now and resolves with their connections by service name ({ name, service, types, plan?, fast }). Call it before the app mounts, so every type the app hands to Atscript UI is the live one; the clients would connect on their first call anyway, and share the same read. It rejects as a client call would for the same failure:ClientErrorwhen the service refuses the read (401UNEXPECTED_CONTENTfor a login page),TransportErrorwhen it cannot be reached or answers no$metadatadocument. An unknown name throwsError.The call
odata<T>(url, options?)is generic like Atscript UI'sTypedClientFactory: the type argument types the client, and nothing checks it at runtime.client(type, options?)answers theODataClientof the entity set a generated type is of, typed by it: its URL isurlOf(type). A type of a value-help service gets the client of that service's set (see Typed clients).urlOf(type)answers the URL the factory serves the type at, under the name of the registration that holds it; before a live service is connected, it reads it from the type's own metadata: the service (@db.space), the entity set (@db.table) and@odata.valueHelpService. It throwsErrorfor a type with no@db.table, one of a service the factory does not register, and, once the service is connected, one of an entity set the live service does not have.urlOf(service, entitySet, valueHelpService?)answers, before a live service is connected, the URL its entity set would have;undefinedfor a service that is not registered or, once connected, an entity set it does not serve.call(handle, input?, opts?)calls an operation of a registered service by its handle of the model module'sops(ODataOperationRef), connecting it first (see Calling an operation). The handle types the call (ODataTypedCallInput):paramsis required when the operation has a required parameter,rowwhen it is called on rows and refused otherwise, and the answer'svalueis its result. A name passed to it rejects with anErrorpointing tocallByName.callByName(operation, input?, opts?)calls an operation by its name, untyped: one only the live service has, or one of a registration without a model. A name ("GetPrice","Ns.release"for a v4 bound operation) is of the factory's only service, a bound one's set ininput.entitySet; with several services pass anODataOperationName, or the call throwsError(so does a service that is not registered).Both calls: the operation is found in the live service by name and binding, its form is the live plan's type of the operation found (not the class the handle's
paramsTypenames), andparamsis validated against it (ClientValidationError).row(an operation on rows) sends its__etagasIf-Matchon a call that writes (a v4 action, a v2 import that is not aGET; a function, and a call on the collection, sendsIf-Match: *on a set with a version token), a412on it aVersionMismatchErrorwith the current token (a 404 when gone); without a token the runner reads the ETag first, last-write-wins (a row that read does not find, or whose call the service answers404, isClientError404NOT_FOUND, as a Moost server answers it).extra(v2 only) sends undeclared parameters untyped. Answers{ value, message?, messages?, details? },valuewhat the operation returned (for the row); fails astoClientErrormaps it, an operation the live service lacksClientError400 withUNKNOWN_OPERATIONon the entry. The calls go with the factory'scalldefaults and the session the service's clients share;opts.signalaborts, andopts.localegoes out asAccept-Language(ODataOperationCallOptions), as the clients send atscript-ui's locale.createBatch(service?)answers a newODataClientBatchof a registered service: the calls of its clients given{ batch }go out as one$batchwhen it is sent. Without a name it is of the factory's only service; with several services, or a name that is not registered, it throwsError. The service need not be connected yet.
import { ops } from "./odata/sales.model.gen";
const { value } = await odata.call(ops.GetPrice, { params: { Material: "M-100" } });
const order = await odata.client(sales.Order).one("4500000001");
await odata.call(ops.OrderSet.ReleaseOrder, { row: order!, params: { Note: "ok" } });
await odata.callByName("Z_RECALC", { params: { Plant: "1000" } }); // only the live service has itODataClientCallOptions
interface ODataClientCallOptions extends TClientCallOptions {
/** How the call goes out: auto-batched (absent), alone (false), or in a batch or changeset. */
batch?: ODataClientBatch | ODataClientChangeset | false;
}The per-call options of the reads and writes of an ODataClient: signal from db-client's TClientCallOptions, and batch. They are the third type parameter of db-client's ClientLike: an ODataClient<T, D> is a ClientLike<T, D, ODataClientCallOptions>, and so is what the factory returns. db-client's own TClientCallOptions is not augmented, so a Client, or a variable typed ClientLike<T> (such as Atscript UI's results), does not take batch. Type a db-client compatible variable with the third parameter to pass it; a ClientLike<T> is assigned to it without a cast:
import type { AtscriptClientShape, ClientLike } from "@atscript/db-client";
import type { ODataClientBatch, ODataClientCallOptions } from "@atscript/odata-client";
const orders: ClientLike<AtscriptClientShape, Record<never, never>, ODataClientCallOptions> = odata(
"/odata/sales/OrderSet",
);
const page = orders.pages({}, 1, 20, { batch });
function pageOf<T extends AtscriptClientShape>(client: ClientLike<T>, batch: ODataClientBatch) {
const typed: ClientLike<T, Record<never, never>, ODataClientCallOptions> = client;
return typed.pages({}, 1, 20, { batch });
}ODataClientBatch
interface ODataClientBatch {
/** A changeset of the batch: the writes given it are applied all or none. */
changeset(): ODataClientChangeset;
/** Sends the queued calls as one $batch; each call's outcome, in call order. */
send(): Promise<PromiseSettledResult<unknown>[]>;
}Calls of the clients of one registered service grouped on purpose into one OData $batch, from createBatch. Give a call { batch } (a read, or a write in a changeset of its own) or { batch: changeset }; it returns its usual promise, which settles once the batch is sent, as the call alone would (toClientError's errors, a 412 part a VersionMismatchError). See Grouping calls on purpose.
send()waits until every call given the batch has queued its request or settled (its validation, the connection, a pre-read it needs), then sends what was queued, onservice.batch(): one$batch, several when it holds more thanmaxPartsrequests, nothing when no call queued one. It resolves, once every call has settled, with each call's outcome in the order the calls were made, and does not reject for a call. A$batchrefused as a whole rejects every call in it with its error; to a service without a batch endpoint (404,405,501) that isClientError400NOT_SUPPORTED, never a missing row, since an explicit batch is not sent again call by call.- The reads given a batch go before its writes, since a write validates its payload first: don't read back a row written in the same batch.
send()a second time throws; so dochangeset()and a call given the batch once it has gone out.
const batch = odata.createBatch("sales");
const changes = batch.changeset();
const orders = odata("/odata/sales/OrderSet");
const a = orders.update({ ...first, Status: "R" }, { batch: changes });
const b = orders.update({ ...second, Status: "R" }, { batch: changes });
const page = orders.pages({ filter: { Status: "O" } }, 1, 20, { batch });
const results = await batch.send();ODataClientChangeset
interface ODataClientChangeset {
/** The batch the changeset is sent with. */
readonly batch: ODataClientBatch;
}A changeset of an ODataClientBatch, from batch.changeset(): the writes given { batch: changeset } are applied all or none. It takes writes only, at the place its first write queues.
When the service refuses it, nothing in it was applied, and every write in it rejects with the changeset's one error, mapped by dbFailureOf and never read as the write's own answer:
| The service answers the changeset | Every write in it |
|---|---|
404, 410 | ClientError 409 CONFLICT, the service's message: no write reads as { matchedCount: 0 } or NOT_FOUND |
412 | ClientError 503 SERIALIZATION_FAILURE: a row changed since it was read; read the rows again and send the batch again. No write is sent again alone, none is a VersionMismatchError |
| any other status | what the write alone would get (400 INVALID_QUERY with the service's messages by field, …) |
The engine's error, with its changeset (size, and on OData v4 the write's contentId), is the cause. A write given the batch itself is a changeset of its own: it answers as alone (a 412 on its token is a VersionMismatchError).
LiveServiceConnection
type LiveServiceConnection = Omit<ODataConnection, "drift" | "refusals">;A service once read, as connect() resolves with it: the engine over the live model, the live types by name (the operation types among them), plan when they were built from the live documents, and fast when the saved ones matched (see ODataConnection). It has no drift report and no operation verdicts.
ODataClientFactoryCallOptions
type ODataClientFactoryCallOptions = Pick<ClientOptions, "metaKey" | "metaStore"> & {
locale?: string;
};The options atscript-ui passes to a client factory, restated so this package does not depend on @atscript/ui.
ODataClientOptions
interface ODataClientOptions {
/** The OData service the entity set belongs to; or `connect` instead. */
service?: ODataService;
/** Entity set name, as in the service model. */
entitySet: string;
/** The annotated type of the entity set: compiled or built at runtime; or `connect` instead. */
type?: TAtscriptAnnotatedType;
/** Resolves with the service and the type when they are not known yet. */
connect?: () => Promise<ODataClientTarget>;
/** Names the client in errors. Default: the type's db.http.path, else the entity set name. */
url?: string;
/** Sent as Accept-Language with every call; a function is read per call. */
locale?: string | (() => string | undefined);
/** Rows query() returns without $limit. Default 1000; 0 reads everything. */
queryLimit?: number;
/** Session, headers and read options of every call. Default: the service's shared session. */
call?: ODataCallInit;
/** With service and type: the service's operations, whose bound ones are the client's actions. */
operations?: ODataOperationConnection;
}The options of new ODataClient(…). Pass service and type, or connect: the factory passes connect for a live service. connect is asked before every call until it resolves; a rejection is the call's. The constructor throws without either. operations is a connection of the service (ODataOperationConnection: the engine, the types, the plan off the fast path); without it the client has no actions. Over a service created with batch: false (what the factory creates for a live registration with batch: false) the client makes no $batch of its own: an action on several rows goes one call per row, an array insert one create per row. A client you create yourself says it on its service: new ODataClient({ service: createODataService({ model, baseUrl, batch: false }), entitySet, type }).
ODataClientTarget
interface ODataClientTarget {
service: ODataService;
type: TAtscriptAnnotatedType;
/** The service's operations, whose ones bound to the set's type are the client's actions. */
operations?: ODataOperationConnection;
}What connect of ODataClientOptions resolves with: the engine and the type a client reads through, and the service's operations (the factory gives them to the clients of the service's own sets, not to those of its value-help services).
ODataOperationName
interface ODataOperationName {
/** The registered service (@db.space). */
service: string;
/** The import name, or for a v4 bound operation its qualified name. */
operation: string;
/** A bound operation: the entity set it is called on. */
entitySet?: string;
}An operation named without its form, for callByName of a factory with several services: one the build does not know, or one of a registration without a model.
ODataOperationCallOptions
interface ODataOperationCallOptions {
signal?: AbortSignal;
/** false: not auto-batched with the calls of the same pass. */
batch?: false;
/** Sent as Accept-Language, unless the factory's locale is "ignore" or its call headers name one. */
locale?: string;
}The third argument of call: a signal that aborts the call, batch: false to send it alone, and the caller's locale, which the service's messages come in. The registration's language is the $metadata's only; data calls and operations carry the caller's locale.
ODataUntypedCallInput
interface ODataUntypedCallInput extends ODataCallInput<
Record<string, unknown>,
Record<string, unknown>
> {
/** With a name, a bound operation: the entity set it is called on. */
entitySet?: string;
}What callByName takes: params, row, extra of ODataCallInput, and the entity set of a bound operation named by a string.
BuildMetaOptions
interface BuildMetaOptions {
model: ServiceModel;
entitySet: string;
type: TAtscriptAnnotatedType;
/** Version and dialect the capabilities are judged for. Default: from the model. */
context?: ProtocolContext;
/** The db actions of the set, as a client lists them. Default: none. */
actions?: readonly TDbActionInfo[];
}ODataClientErrorCode
type ODataClientErrorCode =
| "NOT_SUPPORTED" // 400: not implemented, a write the set refuses, a grouped read it cannot answer, a v2 relation filter or sort
| "UNEXPECTED_CONTENT" // 401: an HTML page (a login redirect) where data was asked for, or a redirected write
| "CAS_NOT_SUPPORTED" // entry of a 400 NOT_SUPPORTED: a $cas that is not the set's version token
| "UNSUPPORTED_ARRAY_OPERATOR" // entry of a 400 NOT_SUPPORTED: $insert, $update, $upsert, $remove
| "UNSUPPORTED_FIELD_OPERATOR" // entry of a 400 NOT_SUPPORTED: $inc, $dec, $mul
| "NOT_FOUND" // 404: remove (or a versioned update) of an entity that does not exist, a set gone live
| "VERSION_MISMATCH"; // 409 VersionMismatchError: a stale version token, the entity's current one in currentVersionThe codes this package puts into a ClientError body by itself. NOT_FOUND and VERSION_MISMATCH carry the body moost-db answers (notFoundError(); kind: "version_mismatch" with currentVersion). A failure of the engine a Moost server answers with a DbError carries the code Moost DB answers it with (dbFailureOf: INVALID_QUERY, NOT_SUPPORTED, CONFLICT, SERIALIZATION_FAILURE, STORE_FAILED, STORE_TIMEOUT, STORE_THROTTLED, with Moost DB's codes on the entries); any other error of the service carries its own code.
ODataClientErrorEntry
type ODataClientErrorEntry = NonNullable<ServerError["errors"]>[number];One entry of a ClientError body's errors list (path, message, optional code and params): the shape an atscript-ui form maps onto its fields.
ODataClientErrorContext
interface ODataClientErrorContext {
model?: ServiceModel;
/** The entity set the failed call addressed. */
entitySet?: string;
/** The URL the client is known by, named in a TransportError. */
url?: string;
/** Of a failed operation call: its parameters (runParameters of @atscript/odata). */
parameters?: readonly string[];
}