Skip to content

Moost Server ​

A Moost server re-serves an OData service through the REST controllers of Atscript DB, so the browser sees a plain Atscript DB backend. @atscript/db-odata makes each entity set a table; you declare one controller per entity set, exactly as with any Moost DB controller, and @atscript/moost-odata gives those controllers their base classes.

ts
// server/main.ts
import { createODataSpace } from "@atscript/db-odata";
import { ReadableController, TableController, provideDbSpace } from "@atscript/moost-db";
import { ODataReadableController, 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! }),
});
// The generated types carry `@db.space 'sales'`: register the space under that name.
provideDbSpace(space, "sales");

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

@ReadableController(sales.Customer, "api/sales/CustomerSet")
export class CustomerSetController extends ODataReadableController<typeof sales.Customer> {}

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

const app = new Moost();
// disableDuplicatePath: app.init() refuses a path registered twice instead of keeping both
app.adapter(new MoostHttp({ router: { disableDuplicatePath: true } })).listen(3000);
app.registerControllers(OrderSetController, CustomerSetController);
await app.init();

init holds the server's own credentials for the service, a technical user: your server authenticates and authorizes its users itself, and the service never sees them. Credentials and Sessions covers the strategies and the sessions the space keeps.

Each entity set is then served with the endpoints of Moost DB, the writes only where the controller extends ODataTableController:

GET    /api/sales/OrderSet/query?CustomerId=C0001&$sort=-OrderDate&$limit=20
GET    /api/sales/OrderSet/pages?$page=2&$size=50
GET    /api/sales/OrderSet/one/4500000001
GET    /api/sales/OrderSet/meta
POST   /api/sales/OrderSet
PATCH  /api/sales/OrderSet
PUT    /api/sales/OrderSet
DELETE /api/sales/OrderSet/4500000001

The browser uses them through @atscript/db-client, which is what Atscript UI does by default: <AsTableRoot url="/api/sales/OrderSet"> needs no client factory of its own.

Connecting ​

await space.connect() reads the live $metadata and the value-help documents the build recorded, with the space's own init, and makes the generated types live (see Live Metadata).

  • Call it once, before app.init(). Moost creates the controllers there, and they read the structure of their tables. A model token binds at app.init(); a table of the space (space.getTable(sales.Order)) can be created at import as well.
  • A failed read rejects connect(), and the app does not start: the ODataError of a refused or failed read, or the parser's Error for an answer that is no $metadata.
  • The drift report, a Moost server feature (the browser has none), goes to the space's logger, else console.warn, once. onDrift replaces it (see Drift report).
  • The server reads once, at start. Restart it to pick up a changed service.
  • connect(init) reads with other credentials than the space's init, for this read only.

The space ​

createODataSpace returns an ODataSpace, an Atscript DB DbSpace whose tables are the entity sets of the service. A type reads the entity set its @db.table names.

The generated types name their service as their @db.space (@db.space 'sales', the plugin's name). Register the space under that name with Moost DB's provideDbSpace(space, "sales"), and a controller binds by model token, as in any Moost DB app: @TableController(sales.Order, "api/sales/OrderSet"). Without a prefix the route is the @db.table name, the entity set's (/OrderSet). The other binding forms of Moost DB work too: a table of the space (@TableController(space.getTable(sales.Order), …)) and a lazy factory (() => space.getTable(sales.Order)). See controller binding.

OptionMeaning
baseUrl, query, …Where and how the service is called: the transport options, as in the browser
model, typesThe generated model module's model and the whole generated module (import * as sales)
nameThe service name. Default: the name the models were generated with
copiesAs in the browser registration (see Live Metadata)
onDrift(drift, message) => … in place of the warning of the drift report
initThe server's credentials and a time limit for every call (see Credentials and Sessions)
sessions{ ttl, max } of the sessions the space keeps, or false for none (see Sessions)
batch{ maxParts }, the most requests one $batch carries (default 100); false sends no $batch at all (below)
searchfalse: a set is searchable only where the metadata declares it (see Search)
logger, onCloseAs on any DbSpace
  • One space per service, registered under the service's name. A relation is read only between tables of the same service.
  • No auto-batching: each request's calls go out as it makes them, with its credentials. A $batch is sent only where one request holds several independent calls: a db action on several rows (see Several rows) and an insert of several rows (see Writes). With batch: false their rows go one call per row, with the same answers; an action whose rows are applied all or none (changeSet) is then refused, 400 NOT_SUPPORTED.
  • The service owns its schema: never sync one over the OData space. In an app that also syncs a database of its own with asc db sync, keep the generated files out of it with the db.exclude option of the Atscript config (exclude: ["src/odata/**"]), or sync would create tables for the OData types. See scoping sync. With Atscript DB's model manifest, the OData types are grouped under their service in modelsBySpace (modelsBySpace.sales): sync your own database from its own group (modelsBySpace.default), not from atscriptModels.

The adapter's capabilities, what each table call sends, and the refusals are listed in the @atscript/db-odata API.

The two base classes ​

ClassEndpointsFor an entity set the service
ODataReadableController/query, /pages, /one, /metalets you read
ODataTableControllerthe same, and POST, PUT, PATCH, DELETElets you create, change or delete in

Both are Moost DB's controllers (AsDbReadableController, AsDbController) with these additions:

  • $search on an entity set the service cannot search is refused with 400. Moost DB itself would answer the rows unsearched.
  • Only the writes the set allows (ODataTableController): /meta lists in crud exactly the writes the service allows, so Atscript UI shows no button that cannot work. Another write is refused before any request with 400 NOT_SUPPORTED, naming why. A set that takes no write at all (not insertable, updatable or deletable; reached only through a navigation; draft-enabled; the parameters of a parameterized view) is served the same way: its reads work, and every write answers 400.
  • A set gone live answers every endpoint 404 (see below), from the bases' prepareRequest.
  • Operations: runOperation() calls an OData operation from a db action, and prepareRequest refuses an operation the live service no longer fits. The plugin generates bases with a db action per operation: see Operations.
  • An ODataReadableController has no write routes: a write answers 404.

Failures of the service need no base: the adapter reports them as Atscript DB's store-failure codes, which every Moost DB controller answers itself (502, 504, 429 with Retry-After) and logs (see Errors).

Moost DB's own classes and Aooth's ARBAC controllers ​

The OData bases extend Moost DB's plain classes: they apply no ARBAC row or field scopes. For scopes, declare the OData table's controller with an ARBAC class of Aooth (AsArbacDbReadableController, AsArbacDbController); it applies them as over any Atscript DB table, without the three additions below.

A controller of Moost DB's own classes (AsDbReadableController, AsDbController) over an OData table works, and so does an ARBAC controller of Aooth: each answers the failures of the service, refused writes and refused reads exactly as the bases do. A class extends one base only, so such a controller goes without the three additions above:

  • $search on a set the service cannot search answers every row, unsearched;
  • /meta lists in crud writes the set does not allow (each is still refused, 400 NOT_SUPPORTED, when called);
  • a set gone live answers every endpoint 500 (logged), not 404.

Three exported helpers of @atscript/moost-odata add them back in a base of your own over such a class:

ts
import type { FilterExpr } from "@atscript/db";
import type { TDbRequestContext } from "@atscript/moost-db";
import type { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
import { AsArbacDbController } from "@aooth/arbac-moost";
import { allowedCrud, refuseGoneEntitySet, refuseUnappliedSearch } from "@atscript/moost-odata";
import { Inherit } from "moost";

@Inherit()
export class SalesArbacTable<T extends TAtscriptAnnotatedType> extends AsArbacDbController<T> {
  protected override async prepareRequest(ctx: TDbRequestContext) {
    refuseGoneEntitySet(this.readable); // a set gone live: 404, as the bases answer it
    await super.prepareRequest(ctx); // ARBAC's own check
  }

  protected override applySearchFallback(
    filter: FilterExpr | undefined,
    controls: Record<string, unknown>,
  ) {
    const applied = super.applySearchFallback(filter, controls);
    refuseUnappliedSearch(this.readable, filter, controls, applied); // 400 on $search
    return applied;
  }

  protected override buildCrud() {
    return allowedCrud(super.buildCrud(), this.readable); // only the writes the set allows
  }
}

Each helper does nothing for a table of another adapter. Over Moost DB's own classes, which have no prepareRequest of their own, call super.prepareRequest?.(ctx).

Sets gone or changed live ​

The server starts on the live $metadata even where it differs from the saved one, and the drift report at start names what changed:

  • An entity set the live service no longer has: every endpoint of its ODataReadableController or ODataTableController, /meta included, answers Moost DB's 404 NOT_FOUND, the answer of a missing row, before any request. A controller of Moost DB's own classes over it answers 500: the adapter throws a plain Error, a fault of the server's build.
  • A set the live service no longer lets you write to: /meta of its ODataTableController drops the refused writes from crud, and such a write is refused with 400 NOT_SUPPORTED.
  • A property that changed: validation and /meta follow the live type, a length the service raised included.
  • An operation that changed or is gone: its db action or route answers 500 or 404, and is out of /meta (see Operations).

Regenerate the models to build against the live service.

Value-help targets ​

Atscript UI finds the target of a foreign key or of a @ui.valueHelp binding through the db.http.path of the target type. Moost DB sets it when the application initializes: the URL of the controller that serves the type, the application's globalPrefix included, provided exactly one controller serves the type at a path without parameters. /meta carries the URL in every reference to the type.

So a value help appears when its target entity set has a controller. A reference to a set nobody serves gets no URL, and the field gets no picker; nothing warns. A target several controllers serve is Moost DB's case: it warns, and the remedy is its canonical: true.

Value-help controllers ​

valueHelpControllers declares the controllers of the value-help targets for you, from the live types. Call it after await space.connect() and before app.init(), and register what it returns next to your own controllers:

ts
import { ArbacResource } from "@aooth/arbac-moost";
import { TableController } from "@atscript/moost-db";
import {
  ODataReadableController,
  ODataTableController,
  valueHelpControllers,
} from "@atscript/moost-odata";
import type { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
import { Inherit } from "moost";

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

@Inherit() // required: Moost passes routes down only through classes marked @Inherit()
@ArbacResource("sales.valueHelp") // your guard: one grant for every value-help route
export class SalesValueHelp<T extends TAtscriptAnnotatedType> extends ODataReadableController<T> {}

await space.connect();

const own = [OrderSetController];
app.registerControllers(
  ...own,
  ...valueHelpControllers(space, { prefix: "api/vh", base: SalesValueHelp, own }),
);
await app.init();
OptionMeaning
prefixThe route prefix of every value-help route
baseThe class each controller extends: ODataReadableController (default), or a subclass of your own, each class marked @Inherit()
ownYour own controller classes: serve the value-help targets of their types, and never a set they serve already

See it live

The Origin and Process dropdowns and the Region picker of coffee 17 in the Moost server app read code lists that valueHelpControllers serves. Code: src/server/main.ts.

Which sets get a controller:

  • Without own: every set of the service's value-help services (OData v4 Common.ValueListReferences, as RAP services of SAP S/4HANA® serve value helps). A value list over a set of the service itself is not served.
  • With own: every @ui.valueHelp target of the types your controllers serve (nested objects included), in the service or in a value-help service, except the sets one of your controllers serves. This is the way for an OData v2 service, whose value lists are sets of the service itself.

Each controller is class extends base {}, named <EntitySet>ValueHelpController for the logs, bound with Moost DB's @ReadableController over space.getTable(Type):

TargetRoute
a set of the service<prefix>/<service>/<EntitySet>: /api/vh/sales/CustomerSet
a set of a value-help service<prefix>/<service>/<value-help service>/<EntitySet>: /api/vh/sales/srvd_f4/sap/zdemo_country_vh/0001/ZDEMO_COUNTRY_VH

The value-help service is its reference path without the .. segments, and the service name keeps the sets of two spaces apart. You never write these URLs: Moost DB publishes each as its target's db.http.path, the globalPrefix included, and the parent's /meta carries it to Atscript UI. The table reads a value-help set at its service's own root, with the space's credentials and session.

The controllers are read-only: there are no write routes (a write answers 404), and $with and relational filters are refused with 400 INVALID_QUERY.

A value-help set that only the live service has (a reference the build could not read, as with a $metadata saved from a browser, or a new one) is among the live types: it gets a controller like any other, and the drift report lists it among the entity sets added.

valueHelpControllers throws before the space is connected, for a space over an engine at hand (it has no types), for a base that is no ODataReadableController (a write base such as ODataTableController) or whose chain misses an @Inherit(), naming the class, and for a route made twice for the space: by a second call with the same prefix and a base of another name, or by two value-help services whose references differ only by . or .. segments. Moost's router keeps a second handler on one path without a word, and runs it when the first one throws: a request the first one's guard refuses would be answered by the twin. A call made again with a base of the same name makes its routes again, so a dev server that reloads the app (@moostjs/vite runs your entry again over the space its unchanged module kept) starts as before. Bases are told apart by name (a class without a name only as itself), so give the classes a factory makes distinct names; disableDuplicatePath is the guard that refuses duplicates at app.init(). Create the HTTP adapter with new MoostHttp({ router: { disableDuplicatePath: true } }), as in the setup above, so that app.init() refuses any path registered twice, whoever made it.

Who may read them ​

  • The service sees the technical user. Every value-help read is made with the space's init, session and language, never as the end user (see Credentials and Sessions). A value-help view the service restricts per user answers what the technical user may read.
  • Your guards are the only check per user: the class guards, interceptors and hooks of base, and the application's global interceptors, exactly as for the controllers you declare. An application with neither exposes these routes to anyone who reaches the server: every row and field the technical user may read in each served set (with own, a set of the service is served whole, not only the columns its value list names).
  • Aooth: a global arbacAuthorizeInterceptor checks the resource and the action. The resource is the base's @ArbacResource, else the generated class name, which can repeat across services: set it on the base. ARBAC row and field scopes do not apply, as for every OData controller; rules per set go into the base's hooks (transformFilter, reading this.boundType).

Limits ​

  • Direct targets only: with own, only the @ui.valueHelp targets of the types you serve, not targets of targets, and no @db.rel.FK target: declare those.
  • Only live types are targets. A target is matched by identity with the space's live types: a @ui.valueHelp you point at an annotate … as copy (or at a type of another space) gets no route. Declare a controller for the copy by hand and pass it in own.
  • Pass every controller of the space in own. A controller of yours over a set the helper serves, left out of own, gives that set two routes: Moost DB warns and publishes no path, and the picker is gone.
  • Sets are fixed at start. A new reference, or a document that becomes readable later, needs a restart. A document that cannot be read at start leaves its fields without a value help.
  • One base for every value-help route; per-set rules go into its hooks.
  • A set whose route would hold a segment outside [A-Za-z0-9_.~-] (a : or * would make a route parameter) gets no route, with a warning on the console.
  • Two spaces need distinct service names. With one name and one prefix they make the same routes, which the helper cannot see across spaces: the router keeps both, so a request one space's guard refuses is answered by the other's controller (a guard bypass), and a picker may read one space's set through the other's root and credentials. disableDuplicatePath turns this into a start failure.

Declaring one by hand ​

A controller you declare still serves its target, at a path of your own and with hooks of its own; pass it in own, and the helper leaves its set alone. A set of a value-help service is a table of the same space like any other:

ts
@ReadableController(sales.CountryVH, "api/sales/vh/CountryVH")
export class CountryVHController extends ODataReadableController<typeof sales.CountryVH> {}

A value-help set named like a set of the service itself gets an interface with a suffix and the same @db.table: give its controller an explicit path, as above, so the two do not claim one route.

Your own base class ​

Hooks shared by the entity sets of a service go into a class of your own between yours and ours. Moost hands routes and constructor injection down only through classes marked @Inherit():

ts
import type { FilterExpr, TDbWriteAction } from "@atscript/db";
import type { TDbControlsType } from "@atscript/moost-db";
import { ODataTableController } from "@atscript/moost-odata";
import type { TAtscriptAnnotatedType } from "@atscript/typescript/utils";
import type { WithRelation } from "@uniqu/core";
import { Inherit } from "moost";

@Inherit()
export class SalesTable<T extends TAtscriptAnnotatedType> extends ODataTableController<T> {
  // Scope the controller's own rows.
  protected override transformFilter(filter: FilterExpr): FilterExpr {
    return { ...filter, SalesOrg: currentSalesOrg() };
  }

  // Stamp every write.
  protected override onWrite(action: TDbWriteAction, data: unknown): unknown {
    return { ...(data as object), SalesOrg: currentSalesOrg() };
  }

  // Scope the related rows $with reads: transformFilter does not reach them.
  protected override validateControls(controls: Record<string, unknown>, type: TDbControlsType) {
    const error = super.validateControls(controls, type);
    if (error) return error;
    for (const entry of (controls.$with ?? []) as WithRelation[]) {
      const scope = { SalesOrg: currentSalesOrg() };
      entry.filter = entry.filter ? { $and: [scope, entry.filter] } : scope;
    }
    return undefined;
  }
}

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

Give the read-only sets an ODataReadableController subclass with the same read hooks. A relation scope goes to the service inside the expansion (Items($filter=SalesOrg eq '1000')); on OData v2, which has no filter in an expansion, such a request is refused with 400 NOT_SUPPORTED, never answered unscoped.

The other hooks of Moost DB (guardWrite, applyMetaOverlay, returnRepresentation, …), custom endpoints and an authorization layer such as Aooth's @ArbacResource / @ArbacAction sit on these classes as on any Moost DB controller. The bases implement prepareRequest (the gone-set check, and the check of the build's operations): an override calls await super.prepareRequest(ctx) first. See Moost DB customization.

See it live

Ordered on Coffees in the Moost server app, the kilograms of every order's items, is a declared decoration, filled in decorateRows with one aggregate() per page of rows. Code: src/server/controllers.ts and src/model/coffee-sales.as.

What /meta says ​

  • Writes: crud lists exactly the writes the set allows (ODataTableController).
  • Filters: filterOps lists the operators the service allows on each field, none on a field it cannot filter by. A request for anything else is refused with 400 before the service is called.
  • Reads: crud lists every query control of Moost DB, also on a set that cannot count; groupable marks fields of a set that cannot aggregate; a mandatory filter is not marked. A request the service cannot answer is refused with 400, or answered 400 by the service with its message.
  • /pages without $sort is ordered by the key, and refused on a set whose key the service cannot sort by.

The browser client's meta() can say more for the same set (count, aggregation); see Limitations.

From scripts and jobs ​

The space works without Moost: a script or a job connects it and reads and writes through its tables, as with any Atscript DB space.

ts
import { createODataSpace } from "@atscript/db-odata";
import { basicAuth } from "@atscript/moost-odata";
import * as sales from "./odata/sales.as";
import { model } from "./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! }),
});
await space.connect();

const orders = space.getTable(sales.Order);
const open = await orders.findMany({
  filter: { Status: "O" },
  controls: { $sort: { OrderDate: -1 }, $limit: 100, $with: [{ name: "Items" }] },
});
await orders.updateOne({ OrderId: "4500000001", Status: "R" });

Every call goes with init's credentials and the session the space keeps for them, as a controller's would; the failures are the same DbErrors (Errors). space.callOperation() runs an operation by its handle of ops, typed by it; space.callOperationByName() one only the live service has (see Operations):

ts
import { ops } from "./odata/sales.model.gen";

// params required as the operation requires them; value typed as its result
const answer = await space.callOperation({
  operation: ops.GetPrice,
  params: { Material: "M-100" },
});

What the compiler checks in these calls, and what it does not (an aggregate()'s rows, for one): Type Safety.

Testing ​

Wooks keeps one router for the whole process, and every Moost HTTP application registers its routes there unless it is given a Wooks instance of its own. A test file that boots a second application at the same paths gets the handlers of the first. Call clearGlobalWooks() (from moost) before creating each application, or give each its own Wooks instance.

A generated module holds one live version per process (see Live Metadata): a test that connects it to a mock serving other documents than an earlier test needs a fresh import of the module, as Vitest gives each test file.

DOs and DON'Ts ​

  • Declare one controller per entity set you serve — nothing declares them for you, save valueHelpControllers for value-help targets; the plugin's controllers option writes operation bases you extend, never controllers.
  • Register the space with provideDbSpace(space, "<service>") and bind controllers by model token — the types carry the service as @db.space.
  • Call await space.connect() before app.init() — the controllers read the structure of their tables when Moost creates them.
  • Give the space the server's own credentials in init — the service never sees your users.
  • Use ODataReadableController for sets you only read — it has no write routes at all.
  • Serve the value-help targets with valueHelpControllers, and every foreign-key target with a controller — a picker needs its target's URL.
  • Pass every controller of the space in own — a set served twice loses its picker.
  • Guard the value-help routes through base or a global interceptor — they read as the technical user, for anyone who reaches them.
  • Mark your own base class with @Inherit() — a plain subclass used as a controller base breaks routing.
  • Call await super.prepareRequest(ctx) first in an override of prepareRequest — skipping it lets a set gone live answer 500 instead of 404, and an operation the live service no longer fits reach its row load.
  • Scope relations in validateControls — don't rely on transformFilter for rows $with reads.

See also ​

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.