Browser Client
@atscript/odata-client lets Atscript UI talk to an OData service directly from the browser. Its ODataClient has every member of the Client of @atscript/db-client (it is a ClientLike), so tables, filters, value-help pickers and forms work with no Atscript server in between.
// 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);showStartError stands for your own code: what the page shows when the service cannot be read. A table of OrderSet is then <AsTableRoot url="/odata/sales/OrderSet">, and every value help that targets an entity set of the service works without further setup.
Connecting
A registration with model and types is live: the factory reads the service's $metadata (and its value-help documents) at runtime and makes the generated types live, as Live Metadata describes.
odata.connect()reads every live service now (connect("sales")reads one) and resolves with the connections by service name:{ name, service, types, plan?, fast }. Mount the app after it, so every type the app hands Atscript UI is the live one.- The browser runs on whatever the live service has. It reports no drift and logs nothing about a change; code that uses a property the live service dropped fails at runtime (see In the browser).
- The imports are live once connected:
createAsFormDef(Order)withOrderimported from./odata/sales.asbuilds the form from the live type. - The clients connect on their first call anyway, and all clients of a service share one read. An app that skips
connect()still gets correct data calls; only a type it used before the connection is the saved one. - Before the read, a URL of a live service already gets a client. 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. A failure rejects
connect()and every call of the service's clients as a data call would: aClientErrorwith the service's status,401UNEXPECTED_CONTENTfor a login page, aTransportErrorwhen nothing answers or the answer is no$metadata.
The read goes out with the browser's login, like every call: the user must be allowed to read the service's $metadata.
How URLs are routed
Atscript UI names every data source by a URL and asks its client factory for a client. The OData factory answers:
<prefix>/<service>/<EntitySet>(default prefix/odata) with anODataClientfor that entity set;<prefix>/<service>/<value-help service>/<EntitySet>with a client for a set of a value-help service (see Value Helps); each segment is URI-encoded, and the factory writes these URLs itself;- every other URL with the
fallback, by default a plain@atscript/db-clientClient. One app can mix OData entity sets with tables of its own Atscript DB backend.
These URLs are names. Nothing is fetched from them: the client calls the service at the registration's baseUrl.
Typed clients
In code, ask the factory for the client of a generated type instead of spelling a URL. The URL is the one the factory serves the type at, under its registration's name (before a live service is connected, read from the type's own @db.space, @db.table, and @odata.valueHelpService for a set of a value-help service), and the client is typed by the type: a misspelled field in a filter, a selection, a write or a row is a compile error.
const orders = odata.client(sales.Order); // ODataClient<typeof sales.Order>
const open = await orders.query({ filter: { Status: "O" }, controls: { $select: ["OrderId"] } });
const url = odata.urlOf(sales.Order); // "/odata/sales/OrderSet": what Atscript UI components take
const typed = odata<typeof sales.Order>(url); // the same client from a URL, typed by the argumentclient(type) and urlOf(type) throw for a type that is no entity set type (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?) still answers a URL by name, or undefined. What the compiler checks in these calls, and what it does not: Type Safety.
Once a service is connected, the factory writes each entity set's URL into its type as db.http.path. That is how Atscript UI finds the target of a foreign key or a @ui.valueHelp binding, in a served type and in a compiled one. So register the factory and connect before the first table or form. A type object carries one URL: registering it with a second factory re-points it there.
Registration options
| Option | Meaning |
|---|---|
baseUrl, query, … | Where and how the service is called: see Reaching the service |
model | The model of the generated model module |
types | The whole generated module (import * as sales from "./odata/sales.as"), imported after your own annotate files |
name | The service's URL segment. Default: the name the models were generated with |
copies | Your annotate … as copies that annotate properties (see Live Metadata) |
session | The session the service's clients make their calls with (see Sessions and CSRF) |
batch | false sends every call alone; { maxParts } caps the requests of one $batch (default 100). See Batching |
search | false: a set is searchable only where the metadata declares it (see Search) |
language, entitySets | Only without model: the language to read the document in, and the entity sets to build (see Without a build step) |
Signatures are in the API reference.
Factory options
| Option | Default | Meaning |
|---|---|---|
services | required | One registration per OData service |
prefix | /odata | URL prefix of the OData entity sets |
fallback | a db-client Client | Creates the client (any ClientLike) of every other URL |
locale | "accept-language" | Send Atscript UI's locale as Accept-Language, or "ignore" it |
queryLimit | 1000 | Rows query() returns without a $limit; 0 reads everything |
call | none | Session, headers and read options of every OData call. Without a session in it, a service's calls use its registration's session, else one session the service's clients share (its value-help sets' clients too) |
A service registered twice is refused. See createODataClientFactory.
Without a build step
A registration without model and types builds the types from the live document, in memory:
import { createODataClientFactory } from "@atscript/odata-client";
import { setDefaultClientFactory } from "@atscript/ui";
const odata = createODataClientFactory({
services: [
{
name: "sales",
baseUrl: "/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
entitySets: ["OrderSet", "CustomerSet"],
language: "EN",
},
],
});
setDefaultClientFactory(odata);
const { sales } = await odata.connect();
// sales.types.Order, sales.plan.skippedThe app waits for the document before its first screen and cannot import the types: it takes them from the connection. plan.skipped lists what the types do not express, as the trailer of a generated file does. Prefer generated models for anything you ship; runtime mode suits tools and prototypes.
Reaching the service
The browser calls the service at baseUrl, so it must be reachable from the page:
- Same origin. Serve the app from the system's own web server, or put both behind one reverse proxy. In development, proxy the service path in Vite (
server.proxy), as the Quick Start does. - Cross-origin needs the service to allow it (CORS), which most SAP Gateway® systems do not. Pass
credentials: "include"in the registration when it does and the login travels in cookies.
The transport options of a registration:
| Option | Use |
|---|---|
baseUrl | The service root, absolute or root-relative |
query | Query options for every call, the $metadata read included, such as { "sap-client": "100" } |
headers | Static headers, or a function called per request (a bearer token you refresh, for example) |
credentials | Passed to fetch ("include" for cross-origin cookies) |
dialect | "sap" or "standard"; by default the one the $metadata fits (see Dialects) |
merge | "tunnel" sends OData v2 MERGE as POST with X-HTTP-Method, for proxies that refuse the verb |
fetch | The fetch to call: for tests, or a wrapper that logs |
The login is the browser's: whoever is signed in to the system (or redirected through single sign-on) is the user the service sees and authorizes. When the service answers with a login page instead of data, or with a redirect where a write was sent (a write is never followed to another address), the client throws a ClientError with status 401, so the app can send the user to sign in again. That holds for a same-origin call and a redirect that carries CORS headers; a redirect to another origin without them is a network error (TransportError), since the browser checks CORS on the 3xx first.
Sessions and CSRF
Every call is made with a session, so the CSRF token a write needs is fetched once and reused. The session is the session of the factory's call option when it names one, else the session of the registration, else one per service that all its clients share. In a browser the cookies themselves are the browser's.
Batching
The clients batch by default, as UI5 does. The calls made in one synchronous pass (a table page and the dropdowns of its filter bar, a form and its value lists) go out as one OData $batch on the next macrotask, instead of one request each:
// One POST $batch, three parts: the page and two value lists.
const [page, customers, currencies] = await Promise.all([
odata.client(sales.Order).pages({ filter: { Status: "O" } }, 1, 20),
odata.client(sales.Customer).query({}),
odata.client(sales.Currency).query({}),
]);- Each call answers what it would alone: its rows,
nullfor a missing entity, its ownClientError. A read is a part of its own and each write a changeset of its own, so a write that fails rolls back no other call. - A pass with one call goes out alone, as a plain request. So does everything a call sends after its first answer: a paging link, the
/$countof a read answered without its count, the read of a row after a412. - One
$batchper service root, session and headers. On SAP Gateway® a page and the value lists of its own service share one; a RAP service reads its value helps from value-help services, each at its own root, so each gets a batch of its own. - A write validates its payload first, and reads it before writing where it carries no
__etag(see Writes): it joins the pass in which it is ready. - The
$batchrequest is a write: the first one of a session fetches the CSRF token, which is then reused for three minutes. - A call of several rows makes its own
$batch: an arrayinsert(a changeset per row, see Writes) and an action on several rows (see Operations). The registration'sbatch: falsesends their rows one by one too; an arrayinsertgiven{ batch: false }as well.
Opt-outs. Batching is off
- for a service registered with
batch: false:services: [{ baseUrl, model, types: sales, batch: false }]; - for a call given
{ batch: false }:client.query(q, { batch: false }); - for a service whose
$metadatasaysCapabilities.BatchSupportedis false; - from the first
$batcha service answers404,405or501(it has no batch endpoint), auto-batched or of a call of several rows: the calls of that batch are sent again one by one, with the answers they get alone (achangeSetaction's are not: it is refused,400NOT_SUPPORTED), and later calls go out unbatched, the rows of a call of several rows one by one, for ten minutes: then a$batchis tried again.
The browser's network tab shows $batch requests instead of single ones; batch: false restores them while you debug.
See it live
Open the network tab on the Overview of the browser app: three grouped reads and a function call go out as one $batch. Code: OverviewScreen.vue (the calls) and src/odata.ts (the factory).
Grouping calls on purpose. odata.createBatch() (name the service when several are registered) collects the calls you give it, and batch.changeset() makes writes that are applied all or none:
// first, second: rows read before, with their __etag
const batch = odata.createBatch();
const changes = batch.changeset();
const orders = odata.client(sales.Order);
const released = orders.update({ ...first, Status: "R" }, { batch: changes });
const closed = orders.update({ ...second, Status: "C" }, { batch: changes });
const page = orders.pages({ filter: { Status: "O" } }, 1, 20, { batch });
const results = await batch.send(); // one PromiseSettledResult per call, in call order- Each call returns its usual promise, which settles once the batch is sent, as the call alone would.
- A changeset the service refuses applied nothing, and every write in it rejects with the changeset's one error, never read as its own: a
404isClientError409CONFLICT(no write answers{ matchedCount: 0 }orNOT_FOUND), a412is 503SERIALIZATION_FAILURE(a row changed since it was read; no write is sent again alone, none is aVersionMismatchError): read the rows again and send the batch again. Any other status is what the write alone would get. send()waits for every call given the batch until its request is queued: its validation, the service's connection, and a pre-read it needs first (which goes out alone, before the batch).- 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.
- A changeset takes writes only; an array
insert,updateorreplace, a set of a value-help service (another root), and a call whose session or headers differ from the first one's (another locale) are refused with aTypeError, before any call. - A batch is sent once:
send()again, or a call given it after it went out, throws. - An explicit batch is sent as a
$batchwhatever the service declares, and never again call by call: to a service without a batch endpoint every call rejects withClientError400NOT_SUPPORTED(never a missing row).
Typing batch. It is an option of the client's own call options, ODataClientCallOptions: the factory's clients (odata.client(sales.Order), odata<T>(url)) are ClientLike<T, D, ODataClientCallOptions> of @atscript/db-client and take it. db-client's options are not extended, so a variable typed ClientLike<T> (what Atscript UI's factories return) or Client<T> does not take batch. Type it with the third parameter; a ClientLike<T> is assigned to it without a cast:
import type { ClientLike } from "@atscript/db-client";
import type { ODataClientCallOptions } from "@atscript/odata-client";
const orders: ClientLike<
typeof sales.Order,
Record<never, never>,
ODataClientCallOptions
> = getDefaultClientFactory()<typeof sales.Order>(odata.urlOf(sales.Order));Signatures: createBatch, ODataClientBatch, ODataClientCallOptions.
Locale
The registration's language (from the models, or given) is the language the $metadata is read in: the labels of the types. It is not sent with data calls. With the default locale: "accept-language", the language Atscript UI asks a client for goes out as Accept-Language with every data call and every action, so texts the service translates (text properties, messages) come back in it; odata.call sends the locale you give it. The labels of the types are those of the live $metadata (see Live Metadata). Use "ignore" to leave the language of the data calls to the service: its sap-language parameter or the user's logon language. An Accept-Language among the factory's call headers wins over both.
What the client does
Client member | ODataClient |
|---|---|
meta(), metaEtag(), invalidateMeta(), getValidator() | Built from the live model and the entity set's type |
query(), count(), pages(), one() | OData reads; one() resolves null for a missing entity |
insert(), update(), replace(), remove() | OData writes where the set allows them (Writes) |
aggregate() | One OData v4 $apply request (Aggregation) |
geoSearch(), geoPages() | Reject: ClientError 400, NOT_SUPPORTED |
action(), availableActions(), getActionForm() | The operations bound to the set (Operations) |
actionOnQuery(), countActionTarget() | Reject: ClientError 400, NOT_SUPPORTED |
meta() answers what a Moost DB /meta answers for the same set: crud lists the reads and exactly the writes the set allows, actions the operations bound to it, every field carries the sort and filter capabilities and filter operators the service declares, versionColumn names the version token, relations the navigations the service expands, and aggregation facts where the set declares $apply. Atscript UI hides what a set cannot do from that.
- Row order. A sort gets the key properties it leaves out appended in the direction of its last key;
pages()without a sort and without a search is ordered by the key. Consecutive pages neither overlap nor skip rows, as far as the set can sort by its key. - Draft-enabled sets (
Common.DraftRoot,Common.DraftNode) are listed and counted for their active entities: a read whose filter has no condition onIsActiveEntitygetsIsActiveEntity eq true, so the user's drafts do not show next to them. Such sets take no write (see Limitations). - Paging links of the service are followed inside one read up to the asked limit; a read that would need more pages than
maxPages(default 100) fails rather than return part of the rows.
DOs and DON'Ts
- Register the factory and mount the app after
odata.connect()— don't hand Atscript UI a type before its service is connected. - Get clients and URLs in code from the generated type (
odata.client(sales.Order),odata.urlOf(sales.Order)) — don't spell/odata/sales/OrderSetby hand. - Pass the whole generated module as
types, after importing yourannotatefiles — don't pick single types out of it. - Set
languagefor the service in the plugin — without it the labels follow the signed-in user's language. - Serve the service from the page's origin or a proxy — don't count on CORS from an SAP system.
- Pass a session in the registration if you need to reach it — the clients use that one.
- Leave batching on — don't turn it off for good to read the network tab; use
batch: falseper call while debugging. - Put writes that must succeed together in one
batch.changeset()— don't count on calls of one pass being atomic: each write is a changeset of its own. - Limit
entitySetsin the plugin to what the app shows — don't ship a whole service's model for a few screens. - Regenerate the models when the service changed — the browser warns about nothing, and code that uses a dropped property fails at runtime.
See also
- Live Metadata: fast and slow path, what the browser does with a changed service, limits.
@atscript/odata-clientAPI: every export and signature.- Atscript UI client factories: per-table and per-form factories.
- Operations: the db actions of a set and
odata.call. - Type Safety: what the typed clients check.
- Errors: what the client throws.