Skip to content

@atscript/db-odata ​

Complete export reference for @atscript/db-odata. See Moost Server for the narrative; the adapter's behavior on reads, writes and relations is covered in Relations, Writes and concurrency and Aggregation.

bash
pnpm add @atscript/db-odata @atscript/odata @atscript/db @atscript/core @atscript/typescript @uniqu/core

One entry point (.), Node. The package plugs an OData service into Atscript DB: its entity sets become tables that work with everything that takes an atscript-db table, the REST controllers of @atscript/moost-db included. Schema sync is never run: the service owns its schema.

"An SAP service" on this page means one whose $metadata an SAP S/4HANA® or SAP Gateway® system produced (RAP services included): the engine detects it and applies the sap dialect.

Classes ​

ODataSpace ​

ts
class ODataSpace extends DbSpace {
  /** The live source; absent on a space over an engine at hand. */
  readonly source?: ODataSource;
  /** The connection, once connect() succeeded (from the start on a fixed space). */
  get connection(): ODataConnection | undefined;
  /** The engine of the connection. Throws before the space is connected. */
  get service(): ODataService;
  connect(init?: ODataAdapterOptions["init"]): Promise<ODataConnection>;
  refusalOf(operation: ODataOperationRef<any, unknown, unknown>): ODataOperationVerdict | undefined;
  callOperation<P, R, K>(
    input: ODataTypedRunInput<P, R, K>,
  ): Promise<ODataCallAnswer<ODataRunValue<R, K>> | null>;
  callOperationByName(input: ODataNamedRunInput): Promise<ODataCallAnswer | null>;
}

The DbSpace createODataSpace returns: space.getTable(Type) as on any space. The generated types name their service as @db.space: register the space under that name with Moost DB's provideDbSpace(space, "sales"), and controllers bind by model token (@TableController(sales.Order, …)). Never run schema sync over it: the service owns its schema.

  • connect(init?) reads the live $metadata and value-help documents, in the language the models were saved in, and makes the generated types live (createODataSource). It reads with the space's own init; its argument is an optional override. Call it once before app.init(): Moost creates the controllers there, and they read the tables' structure. It resolves with the same connection ever after. What the live metadata changed against the saved one is warned once through the space's logger (else console.warn), unless onDrift takes it. Rejects with what reading $metadata throws: the ODataError of a refused or failed read, the parser's Error for an answer that is no $metadata document.
  • service throws Error until the space is connected.
  • source is the live source of the space, for its name, model and language.
  • refusalOf(handle) is the verdict of an operation of the build the live service no longer fits: gone (it no longer has it) or incompatible (the build's calls no longer fit it), with the reason; undefined when it fits. A live space computes the verdicts once, on connect(), when the live $metadata differs from the saved one, and lists them in the drift report (operationVerdicts). The OData bases of @atscript/moost-odata refuse such an operation 404 or 500.
  • callOperation(input) calls an operation by its handle of ops (runOperation) with the space's credentials, the session it keeps for them and its language, as the tables' calls are made: an unbound one, or a bound one (a table calls its own through ODataAdapter.callOperation). The handle types the call (ODataTypedRunInput): params is required when the operation has a required parameter, rows when it is called on rows, and the answer's value is its result, one per row on rows. callOperationByName(input) calls one only the live service has by name, untyped; a bound one names its set in entitySet. An operation the live service no longer fits is refused: OPERATION_GONE (400) or a plain Error; the parameters are validated against the live operation type (the validator's ValidatorError); what the call throws, and the error of each row in failed, is mapped as a table's callOperation maps it (see ODataAdapter, Operations): a 412 on the row's own __etag is that row's version mismatch, for you to answer (one row resolves null, a row of several is { index, error: null } in failed), a row the service has no entity for a DbError NOT_FOUND, the rest as the tables' calls (toDbError). Throws Error before the space is connected. The operations base of @atscript/moost-odata calls it, on no rows: it never resolves null there.

ODataAdapter ​

ts
class ODataAdapter extends BaseDbAdapter {
  constructor(
    service: ODataService | (() => ODataService | undefined),
    options?: ODataAdapterOptions,
  );

  readonly options: ODataAdapterOptions;
  /** The service the table is read from (a value-help service's engine for its types). */
  get service(): ODataService;
  /** The live service no longer has the entity set (a live space only). */
  get gone(): boolean;
  /** The entity set this adapter reads, as the query layer describes it. */
  get entitySet(): EntitySetDescription;
  /** The writes the service model allows on the entity set. */
  get allowedWrites(): Record<EntitySetWrite, boolean>;
  refusalOf(operation: ODataOperationRef<any, unknown, unknown>): ODataOperationVerdict | undefined;
  callOperation<P, R, K>(
    input: ODataTypedRunInput<P, R, K>,
  ): Promise<ODataCallAnswer<ODataRunValue<R, K>> | null>;
  callOperationByName(
    input: Omit<ODataNamedRunInput, "entitySet">,
  ): Promise<ODataCallAnswer | null>;
}

The @atscript/db adapter over one entity set; one instance per table. Its entity set is the table's name (@db.table, which the generator writes as the entity set's name). createODataSpace creates one per table for you, so construct it yourself only to build a DbSpace by hand.

Operations. callOperation(input) calls an operation bound to the entity set by its handle (runOperation, the entity set filled in; typed as the space's), callOperationByName(input) one only the live service has by name, with the space's credentials and session: on the collection, or on rows (each with its key and, on a set with a version token, its __etag, sent as If-Match on a call that writes). The handle of an unbound operation is called unbound; a function, and a call on the collection, sends If-Match: * on a set with a version token. A 412 on the row's own __etag (sent by a call that writes; sendsRowToken) resolves null: the entity changed since the caller read it, a version mismatch for the caller to answer (the OData bases answer 409 VERSION_MISMATCH with the current token). Code of your own that calls it answers as they do: read the row, then throw moost-db's versionMismatchError(row.__etag), or notFoundError() when it is gone. Without the token the ETag is read right before the call (* where the set cannot be read from the root, or the entity comes without one), and read again after a 412 (three attempts, then SERIALIZATION_FAILURE). A row the service has no entity for (that read finds none, its call then not sent; or the call is answered 404 or 410) is a DbError NOT_FOUND, which the OData bases answer with moost-db's notFoundError(): do so in code of your own. Everything else throws as the table's calls do. Several rows go out as one $batch by input.grouping: each failed row of an isolated run is in failed, its error mapped as a call on that row alone (a DbError, or null for a 412 on its own __etag); a refused changeSet run throws its one DbError, a message that names a row at that row ([1]). refusalOf(handle) is the verdict that refuses an operation, as on ODataSpace. Both need the space's connection (ODataAdapterOptions.connection), which createODataSpace gives.

service may be a function that answers the engine once it is known: a live space connects after its tables are created. service, gone and entitySet throw Error before then. On a set the live service no longer has (gone), every call throws a plain Error before any request (the server's build no longer fits the service: Moost DB answers 500); the controller bases of @atscript/moost-odata answer such a table 404 first. allowedWrites are the live service's. Every failure is a DbError (toDbError).

What it declares to the table layer, and so what /meta and the table layer's own checks follow:

CapabilityAnswer
supportsNestedObjects()true: complex types are nested objects, paths arrive as Address.City
supportsNativeForeignKeys()true: referential integrity is the service's business
supportsWithInRead()true: the relations of $with ride the read as $expand
supportsRelationFilters(mode)read: a filter by a related row of a to-one navigation ($some / $none), OData v4; see below
sharesStoreWith(other)only a table of the same service
canFilterField, canSortField, filterOpsfrom the service model; a key or foreign key always takes $eq and $in
isSearchable(), getSearchIndexes()the entity set's free-text search, as one index named ODATA_SEARCH_INDEX
aggregateFns()the functions of the set's $apply; none on OData v2
nativeDefaultFns()store: values the service fills in (@db.default.store)
supportsVersionTokens()true: the ETag is the version token (@db.column.version.token)
MethodOData
findOne, findMany, count, findManyWithCountkey read, $filter / $select / $orderby / $skip / $top, /$count, inline count
search, searchWithCountsearch (v2) or $search (v4), where the set allows it
aggregateone $apply request (OData v4)
insertOne, insertManyPOST; several rows one $batch, a changeset per row (one by one with batch: false); see below
updateOne, replaceOne, deleteOneMERGE / PATCH, PUT, DELETE of one entity by key
updateMany, replaceMany, deleteManyrefused with ODataNotSupportedError
ensureTabledoes nothing

Filters by a related row. A read, a count and an aggregate() take $some / $none on a to-one navigation of the same service, sent as its navigation path in $filter or in the filter() of the $apply. Any other relational predicate (to-many, OData v2, a navigation the set does not let a filter use, a write) is refused before any request with REL_FILTER_NOT_SUPPORTED. See Filtering by a related row.

insertMany of several rows sends one $batch, each row in a changeset of its own (one POST after the other with the space's batch: false or on a service without $batch): not atomic, the rows after a refused one still run. Every row created: { insertedCount, insertedIds }. Rows refused: a DbError with the first refused row's code, its message "k of N rows were created; the row at [i] failed", every refused row's entries at that row ([1].City) and an entry { path: "[j]", code: "INSERTED", params: { insertedId } } per row created; every row refused: the first row's message, no INSERTED entry (rowsFailure). See Several rows at once.

ODataNotSupportedError ​

ts
class ODataNotSupportedError extends DbError {
  name: string;
  /** The adapter method that was called (insertMany, updateOne, deleteMany, aggregate, …). */
  readonly operation: string;
  constructor(
    operation: string,
    entitySet: string,
    message?: string,
    cause?: unknown,
    entry?: { path?: string; code?: string },
  );
}

An operation the adapter refuses before any request: one OData cannot express (a write by filter, a field operator, a grouped read $apply has no form for), or one the service model does not allow (a write to a set that is not insertable, updatable or deletable, or is draft-enabled). A DbError with code NOT_SUPPORTED, which moost-db answers 400. Its one entry has no params, as Moost DB's own NOT_SUPPORTED, and is coded NOT_SUPPORTED, or as the browser client codes the same refusal (entry): a field operator UNSUPPORTED_FIELD_OPERATOR at its field, a version number CAS_NOT_SUPPORTED at $cas. The browser client answers a write the set does not allow, and a grouped read it cannot answer, with the same entry (dbFailureOf).

Functions ​

createODataSpace ​

ts
function createODataSpace(options: ODataSpaceOptions): ODataSpace;

Creates a ODataSpace whose tables are the entity sets of one OData service: space.getTable(Order) returns a table that reads the entity set Order was generated from. A type of one of the service's value-help services (@odata.valueHelpService) is read at that service's root, with the space's init.

The live form (ODataLiveSpaceOptions) reads the service's $metadata with space.connect(). Register it under the types' @db.space with provideDbSpace, and connect before app.init():

ts
// server/main.ts
import { createODataSpace } from "@atscript/db-odata";
import { TableController, provideDbSpace } from "@atscript/moost-db";
import { ODataTableController, basicAuth } from "@atscript/moost-odata";
import { MoostHttp } from "@moostjs/event-http";
import { Moost } from "moost";
import * as sales from "../src/odata/sales.as";
import { model } from "../src/odata/sales.model.gen";

const space = createODataSpace({
  baseUrl: "https://my-gateway.example.com/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
  query: { "sap-client": "100" },
  model,
  types: sales,
  init: basicAuth({ user: process.env.ODATA_USER!, password: process.env.ODATA_PASSWORD! }),
});
provideDbSpace(space, "sales"); // the types' @db.space

@TableController(sales.Order, "api/sales/OrderSet")
export class OrderSetController extends ODataTableController<typeof sales.Order> {}

await space.connect(); // the live $metadata, before app.init()

const app = new Moost();
app.adapter(new MoostHttp()).listen(3000);
app.registerControllers(OrderSetController);
await app.init();

Every call of a table is made with:

  • the space's init: the credentials the server was given for the service, a time limit (see @atscript/moost-odata).
  • the session the space keeps for the credentials it sends: one per credential, so two credentials never share a session or a CSRF token. See ODataSessionOptions.
  • the saved language: when the models name a language, Accept-Language: <language> on every data call, unless init sets one, so labels and data texts come in one language.

An entity set the live service no longer has keeps its table: every call of it throws a plain Error (Moost DB: 500; the OData controller bases answer 404 first), and the drift warning names it.

The fixed form (ODataFixedSpaceOptions) takes an engine at hand and reads no $metadata; it is connected from the start. Use it for tests and tools:

ts
import { createODataService } from "@atscript/odata";
import { createODataSpace } from "@atscript/db-odata";
import { model } from "./odata/sales.model.gen";
import { Order } from "./odata/sales.as";

const service = createODataService({
  model,
  baseUrl: "https://host/sap/opu/odata/sap/ZDEMO_ORDERS_SRV",
});
const space = createODataSpace({
  service,
  init: () => ({ headers: { Authorization: process.env.ODATA_AUTHORIZATION! } }),
});

const orders = space.getTable(Order);
await orders.findMany({
  filter: { CustomerId: "C0001" },
  controls: { $limit: 20, $with: [{ name: "Items" }] },
});

Over a model parsed from the $metadata alone, getTable of a value-help service type throws: create the engine from the generated model module. See Credentials and sessions.

toDbError ​

ts
function toDbError(
  error: unknown,
  entitySet: string,
  model?: ServiceModel,
  parameters?: readonly string[],
): unknown;

Turns what the OData engine throws into the DbError the atscript-db stack expects, with the original as cause. For a failed operation call, parameters (runParameters) reports a message about a parameter at it. The adapter applies it to every call; use it only in code of your own that calls the engine directly and should answer like a table.

  • every failure dbFailureOf of @atscript/odata maps (a refused read or write, a value that cannot be written, a read past maxPages, the service's 400, 409, 412, 429 and 5xx) becomes a DbError with that code and those entries: the one mapping the browser client answers with too;
  • any other failure of the service is a call the service did not serve: STORE_TIMEOUT when the call was aborted (callTimeout), else STORE_FAILED (no answer, the server's credentials refused, a write without a session, a login page, a redirect answering a write, an answer that is no OData, another status; a precondition the service demands and its metadata does not declare, 428 or a 412 to no If-Match, with a message that says so and the entry code PRECONDITION_REQUIRED). One entry at "" with a generic message; what the service said stays in cause.

Moost DB answers the store-failure codes 502, 504 and 429 (with Retry-After from the entry's params.retryAfter) and logs every 5xx with its cause; see Errors. Anything else (a DbError, an error of init) is returned as it is. model maps the targets of the service's messages to field paths.

isODataNotSupportedError ​

ts
function isODataNotSupportedError(value: unknown): value is ODataNotSupportedError;

Also true for an ODataNotSupportedError created by another copy of this package.

Constants ​

DEFAULT_SESSION_TTL ​

ts
const DEFAULT_SESSION_TTL: number; // 30 minutes, in milliseconds

How long an unused session is kept unless sessions.ttl says otherwise.

DEFAULT_MAX_SESSIONS ​

ts
const DEFAULT_MAX_SESSIONS = 1000;

How many sessions a space keeps unless sessions.max says otherwise.

ODATA_SEARCH_INDEX ​

ts
const ODATA_SEARCH_INDEX = "DEFAULT";

The name of the one search index an entity set with free-text search has. A search that names another index is refused.

Types ​

ODataSpaceOptions ​

ts
type ODataSpaceOptions = ODataLiveSpaceOptions | ODataFixedSpaceOptions;

The options of createODataSpace: live, or over an engine at hand.

ODataLiveSpaceOptions ​

ts
type ODataLiveSpaceOptions = Omit<ODataSourceOptions, "verdicts" | "batch"> &
  Pick<TDbSpaceOptions, "logger" | "onClose"> & {
    /** $batch settings: maxParts only (a Moost server never auto-batches); false: no $batch at all. */
    batch?: false | { maxParts?: number };
    /** What every call to the service is made with; see ODataAdapterOptions. */
    init?: () => ODataCallInit | undefined | Promise<ODataCallInit | undefined>;
    /** The sessions the space keeps with the service, or false for none. */
    sessions?: ODataSessionOptions | false;
  };

A live space: everything ODataSourceOptions takes but verdicts, which a space always sets (it holds the live service to the build's operations), and the space's own options. Its engine never auto-batches (batch.auto is the browser's: see auto-batching): every call goes out as the request that made it sends it. A $batch goes out only where one table call holds several independent calls: an operation on several rows (callOperation).

OptionMeaning
baseUrl, query, headers, dialect, merge, fetch, csrf, read, write, search, …The transport options and settings of the engine (ODataConnectOptions); search: false keeps search only where the metadata declares it (ODataServiceSettings).
model, typesThe generated model module's model and the generated .as module, whole (import * as sales).
copies, nameSee ODataSourceOptions.
onDriftReceives the drift report, operations included. Default: a warning through logger, else console.warn.
initThe credentials of the server for the service, called once per table operation; also what connect() reads with by default.
sessions{ ttl, max } of the sessions the space keeps (ODataSessionOptions); false for none (writes to an SAP service then fail).
batch{ maxParts }, the most requests of one $batch (default 100). false: no $batch (its services are created with batch: false); an operation on several rows goes one call per row (refused, NOT_SUPPORTED, for a changeSet run), the space's own callOperation too.
logger, onCloseAs on any DbSpace.

ODataFixedSpaceOptions ​

ts
type ODataFixedSpaceOptions = Pick<TDbSpaceOptions, "logger" | "onClose"> & {
  /** The OData service whose entity sets are the tables of the space. */
  service: ODataService;
  init?: () => ODataCallInit | undefined | Promise<ODataCallInit | undefined>;
  sessions?: ODataSessionOptions | false;
};

A space over an engine at hand, read from no $metadata: for tests and tools. init and sessions work as on a live space. No $batch, as a live space's batch: false, is the service's own option (ODataServiceTransportOptions): createODataSpace({ service: createODataService({ model, baseUrl, batch: false }) }).

ODataSessionOptions ​

ts
interface ODataSessionOptions {
  /** Milliseconds a session is kept after its last use. Default DEFAULT_SESSION_TTL. */
  ttl?: number;
  /** The most sessions kept at once. Default DEFAULT_MAX_SESSIONS. */
  max?: number;
}

The sessions a space keeps with the service: the service's cookies and the CSRF token a write needs. The space keeps one per credential its calls send, told apart by the SHA-256 of the call's headers except Accept-Language, so two credentials never share a session. With one technical user that is one session; a rotating token starts a new one. Calls without credentials stay stateless. A call whose init brings a session of its own keeps it. One more session than max drops the one unused for the longest time; a dropped session is no error, the next call starts a new one. Keep ttl at or below the idle timeout of the service's own sessions. A ttl or max that is not a positive number throws. See Sessions.

ODataAdapterOptions ​

ts
interface ODataAdapterOptions {
  /** Called once per adapter operation: session, headers, signal, read options of every call. */
  init?: () => ODataCallInit | undefined | Promise<ODataCallInit | undefined>;
  /** The saved model of a live space: describes a set the live service no longer has. */
  saved?: ServiceModel;
  /** The space's connection, once connected: what operations run on. */
  connection?: () => ODataConnection | undefined;
}

init runs at the time of the call, so it may read the request context; the reads a write makes (its ETag read, the CSRF fetch) and the write itself carry the same answer. An error it throws reaches the caller unchanged. In Node every write to an SAP service needs a session in it; a space puts one in for you. saved is what createODataSpace gives the adapters of a live space: a set the live service no longer has is described by it, and every call of its table is refused as gone. connection is the space's connection, which callOperation runs on; createODataSpace gives it. Whether several rows go out as one $batch is the service's: one created with batch: false sends none. See ODataCallInit.

SAP, SAP S/4HANA, SAP Fiori, SAPUI5, SAP BTP and other SAP products and services mentioned herein, as well as their respective logos, are trademarks or registered trademarks of SAP SE (or an SAP affiliate company) in Germany and other countries. Atscript OData is an independent open-source project and is not affiliated with, sponsored or endorsed by SAP SE.
Released under the MIT License.