Skip to content

Generating Models ​

A service's $metadata becomes Atscript types in two steps: save the document once with atscript-odata fetch, then let the build plugin of @atscript/odata generate a .as file and a model module from it on every build. At runtime the hosts read the live $metadata and run on it (Live Metadata); the saved file types your code.

ts
// atscript.config.ts
odataPlugin({
  services: [{ name: "sales", metadata: "odata/sales.xml", language: "EN" }],
});

Save the $metadata ​

The simplest way: open the service's $metadata URL in a browser where you are signed in and save the page. That works behind single sign-on; set the plugin's language to the language that browser session was in. The CLI does the same from a script, when the service accepts basic authentication or a header you pass, and also saves the value-help documents of an OData v4 service:

bash
ODATA_USER=me ODATA_PASSWORD=… npx atscript-odata fetch \
  'https://my-gateway.example.com/sap/opu/odata/sap/ZDEMO_ORDERS_SRV/$metadata' \
  --out src/odata/sales.xml --query sap-client=100 --language EN
  • Language: --language EN reads every document in that language (as sap-language and Accept-Language) and writes it into the manifest beside the file, where the plugin takes it as the service's language. Without it the CLI says so: the documents are in the language the service picked.
  • Credentials: basic authentication from ODATA_USER / ODATA_PASSWORD (or --user / --password). A token goes in --header "Authorization: Bearer …", which wins over basic authentication.
  • Extra headers and query options for every call: --header "Name: value" and --query name=value, both repeatable.
  • Value-help documents. For an OData v4 service whose properties name their value lists by reference (Common.ValueListReferences, as RAP services of SAP S/4HANA® serve value helps), the command also reads the first referenced document of each property and saves it in src/odata/sales.value-helps/, with a manifest src/odata/sales.value-helps.json the plugin reads by itself. See Value Helps.
  • Refresh by running it again: files whose content did not change are not rewritten, documents of references that are gone are removed.
  • Exit code 0 when everything was saved, 1 when something could not be read (the rest is saved, and a value-help document an earlier fetch saved for a failed reference is kept), 2 for a usage error.

The same is available as a function, fetchODataMetadata({ url, out, headers, query, language }) of @atscript/odata/plugin. Every flag is listed in the API reference.

However it was saved (a browser, the CLI, a colleague, a support ticket), the plugin only needs the file. Saved as the service sent it, it lets the hosts take the fast path at runtime; a copy reformatted beyond whitespace never does (see Live Metadata).

Commit the metadata

The saved $metadata is the input of every build. Commit it with your code, so a build never depends on reaching the service, and a change of the service shows up as a diff.

Configure the plugin ​

ts
// atscript.config.ts
import { defineConfig } from "@atscript/core";
import ts from "@atscript/typescript";
import dbPlugin from "@atscript/db/plugin";
import uiPlugin from "@atscript/ui/plugin";
import odataPlugin from "@atscript/odata/plugin";

export default defineConfig({
  rootDir: "src",
  plugins: [
    ts(),
    dbPlugin(),
    uiPlugin(),
    odataPlugin({
      services: [
        { name: "sales", metadata: "odata/sales.xml", language: "EN" },
        {
          name: "masterData",
          metadata: "odata/master.xml",
          entitySets: ["CustomerSet", "PlantSet"],
          language: "EN",
        },
      ],
    }),
  ],
});

The generated types use annotations of @atscript/db and @atscript/ui: keep dbPlugin() and uiPlugin() in the list.

Service options ​

OptionDefaultMeaning
namerequiredThe service's name in your app. Written as @db.space, the name a Moost server registers its space under; the browser client uses it as a URL segment. default, the space of your own database, is refused.
metadatarequiredPath of the saved $metadata document.
outputmetadata with the extension .asPath of the generated .as file. Keep it inside rootDir, or Atscript does not compile it.
modeloutput with .model.gen.tsPath of the model module, or false to write none.
entitySetsallGenerate only these entity sets and what their interfaces reference (types, relation and value-help targets). The model is cut alike.
valueHelpsthe manifest beside metadata{ [reference]: path } of value-help documents saved by hand. An entry wins over the manifest's. See Value Helps.
languagethe manifest's languageThe language the file was saved in: an SAP language code (EN) or a language tag (en). The hosts read the live $metadata in it. Without one, the .as file ends with a note. See Live Metadata.
operationsevery operation{ exclude: [...] }: operations left out of the types, the handles, the controllers and the model, by import, local or qualified name. See Operations.
controllersofftrue, or { output?, writable? }: also write the controllers module of a Moost server. Needs the model module. See Operations.

Plugin options ​

OptionDefaultMeaning
services[]The services to generate.
rootthe Atscript rootDirAbsolute directory relative paths are taken from (import.meta.dirname, or a metadata folder outside rootDir).

entitySets is the way to keep a browser bundle small: a large service yields a large model module, and a screen rarely needs every set.

What is generated ​

Two files per service, next to the metadata unless output and model say otherwise, and with controllers a third, the controllers module of a Moost server.

See it live

The labels, columns, filters and pickers of Coffees in the browser app come from the generated types. Code: atscript.config.ts and src/generated/.

The .as file ​

One exported interface per entity set, named after its entity type:

atscript
@db.table 'OrderSet'
@db.space 'sales'
@meta.label 'Sales Order'
export interface Order {
    @meta.id
    @meta.label 'Order'
    @meta.description 'Sales order number'
    @meta.readonly
    @db.default.store
    @normalize.uppercase
    OrderId: string
    // …
}

Complex types become named interfaces, enumerations unions of string literals. The facts the service declares map onto annotations Atscript DB and Atscript UI already read:

In the $metadataIn the generated type
entity setan exported interface with @db.table (the entity set) and @db.space (the service name)
label of the type@meta.label
key property@meta.id
label (sap:label, Common.Label, else Display.DisplayName), heading, quick info of a property@meta.label (the heading when there is no label), @meta.description
MaxLength@expect.maxLength
computed property@meta.readonly; a scalar also @db.default.store (the service fills it, so a create need not)
a GUID the service fills in when left out (Core.ComputedDefaultValue)@db.default.uuid
upper case only@normalize.uppercase
hidden@ui.table.exclude and @ui.form.hidden
amount with its currency, quantity with its unit@db.amount.currency.ref, @db.unit.ref
precision and scale of a decimal@db.column.precision
optimistic concurrency of the entity seta field __etag: string with @db.column.version and @db.column.version.token
text of a code (Common.Text, sap:text) with its arrangement@ui.valueLabel (see Value Helps)
text of the single key@ui.dict.label on the text (see Value Helps)
value list, fixed values@ui.valueHelp with .fill and .column; @ui.type 'select' (see Value Helps)
navigation@db.rel.FK with @db.rel.to / .from, or @db.rel.store (see Relations)

What the hosts need beyond the types (which fields can be sorted and filtered, which writes a set allows, whether it can count, search or aggregate) stays in the model module and reaches /meta from there.

An entity type served by several entity sets is emitted once as a plain interface, with one @db.table interface per set that extends it.

Edm types ​

EdmAtscriptNote
Stringstring
Booleanboolean
Byte, SByte, Int16, Int32number.int.uint8, .int8, .int16, .int32
Int64number.int.int64values beyond 2^53 lose precision
Decimaldecimala string on the wire and in your rows; declare it
Double, Singlenumber.double, number.single
Guidstring.uuid
DateTime (v2) with a date-only formatstring.dateYYYY-MM-DD, read in UTC
DateTime (v2), otherwisenumber.timestampepoch milliseconds; the value has no time zone
DateTimeOffsetstring.isoDate
Date (v4)string.date
TimeOfDay (v4), Time (v2)string with an HH:MM:SS pattern
Durationstring with an ISO 8601 duration pattern
Binarystringbase64
enumerationa union of the member namesa flags enumeration becomes string
complex typea named interface
Collection(T)T[]
nullablean optional property (?)
Stream, geography and geometry, Untypedleft outlisted in the trailer

The codecs convert between the wire form of each OData version and these values, both ways: your code sees the same row whether the service speaks v2 or v4.

The model module ​

ts
// src/odata/sales.model.gen.ts (generated)
import type { ServiceModel } from "@atscript/odata";

export const model: ServiceModel = JSON.parse('{"version":"v2", …}');
export default model;

It holds what the runtime layers work from: entity sets and their capabilities, keys, navigations, value lists, value-help services, operations. Its model.build records what the plugin built from: the service name, entitySets, language and a digest of each saved document. The hosts compare the live documents with it; you never write it. Hand it to a host together with the whole generated .as module, { baseUrl, model, types: sales }, in a browser registration or a space.

When the live $metadata is the saved one, the app parses nothing at runtime. The module holds no raw vocabulary annotations, only the facts the layers read out of them.

Operations ​

Every function import, action and function of the service gets an interface <Name>Params at the end of the .as file: its form, the parameters a caller gives. <Name> is the import name; for a bound OData v4 operation, the interface name of its entity type and its local name (OrderRelease).

atscript
@meta.label 'Release'
export interface ReleaseOrderParams {
    @meta.label 'Note'
    @expect.maxLength 40
    Note?: string
}
  • Plain interfaces: the operation's label, and its parameters as entity properties are written (labels, lengths, precision, ? for a nullable or optional parameter). An operation called on rows leaves out the parameters the row's key fills.
  • The facts stay in the model module: whether a row can take the operation (available), how several rows are grouped (grouping). The hosts take them from there.
  • The model module exports ops, a typed handle per operation: unbound ones by import name (ops.GetPrice), bound ones under their entity set by local name (ops.OrderSet.ReleaseOrder). A handle names the operation and its form, and carries the parameter, result and row types.
  • Never generated: draft lifecycle operations, and one the service marks never available. operations.exclude leaves out more.

A Moost server serves them through the controllers module, which the controllers option writes; the browser client lists and calls them by itself (see Operations in the browser).

The trailer: what the types cannot express ​

The .as file ends with a comment block that lists everything the service declares and the types do not express, one line each, with the reason:

atscript
// Not expressed in these types (9):
// - demo.shop.types.v1.Permission: enumeration members (a flags enumeration combines members in one value, which a union of literals cannot hold; emitted as string)
// - demo.shop.types.v1.PostalAddress/position: property (Edm.Geography has no Atscript type)
// - demo.shop.v1.Order/items: navigation (target demo.shop.v1.OrderItem has no entity set; @db.rel.* needs a @db.table interface on both ends)
// - demo.shop.v1.Order/status: value list (its values are in another service (../lookup/))
// - demo.shop.v1.Order/customer_id: text customer/name (the text is not a text property next to this one)
// - demo.shop.v1.Order/payload: property (Edm.Untyped has no Atscript type)
// - demo.shop.v1.OrderItem/order: navigation (demo.shop.v1.OrderItem has no entity set; @db.rel.* needs a @db.table interface on both ends)
// - demo.shop.v1.Customer: media stream (media entities are emitted as plain entities; the stream is not exposed yet)
// - Me: singleton (singletons are not emitted yet)

Nothing is dropped in silence. What you typically find there:

  • Value lists the generator does not bind: the lists after the first of a property, lists in another service (CollectionRoot), lists whose mapping is in a separate OData v2 annotation document, lists that would repeat a value. See Value Helps.
  • Properties without an Atscript type: streams, geography and geometry, Edm.Untyped.
  • Navigations without exactly one target table: to a type no entity set serves (a contained one, for example).
  • Singletons and media streams, which are not emitted yet.
  • Operations left out: one whose types fall outside the selected entity sets, one the engine cannot call (a structured OData v2 parameter, a structured v4 function parameter, overloads bound alike), an availability path no row can be checked by.
  • Texts the generator cannot place: a text through a navigation path, or on a code whose value help does not fill it.

Read the trailer after the first generation and after every metadata change. Each line is either something you can live with, or a hint for an annotate block of your own. A service without language gets one more line, a note that the hosts read the live $metadata in whatever language the service picks.

When the files are generated ​

  • asc and bundler builds generate. Every asc run, every bundler build, watch rebuild and dev server start regenerates before reading any .as file. A file is rewritten only when its content changes.
  • What fails the build: a missing or unreadable metadata file, an unreadable value-help manifest, an unknown name in entitySets, operations.exclude or controllers.writable, controllers without the model module. A missing value-help document does not: the property stays without a value help and is listed in the trailer.
  • The editor does not generate. It reads the files the last build left. After replacing a $metadata file, run asc once (or restart the dev server).
  • Generate on install with "prepare": "asc -f dts", so a fresh checkout has the files before the editor or the type checker needs them. If you commit the generated files instead, commit both.
  • One root for every host. A relative rootDir resolves against the folder of atscript.config.*, and a missing one is that folder, in asc, the bundler and the editor alike: the service paths mean the same everywhere. Set the plugin's root only for metadata kept outside rootDir.

Enrich the generated types ​

The generated files are overwritten. Labels, validation and UI hints of your own go into annotate blocks in a .as file of yours:

atscript
// src/odata/sales-ui.as
import { Order } from './sales'

annotate Order {
    @meta.label 'Ordered on'
    @ui.form.order 1
    OrderDate

    @expect.pattern '^[^@]+@[^@]+$', '', 'Enter an e-mail address'
    ContactEmail
}

A block like this changes Order itself, for every host, and it stays on the live type at runtime (see Live Metadata). Because the generated file cannot import yours, the compiler warns that the block "applies only in builds including this file". Import the file with your blocks once at startup, before the first table, form or space is created (import "./odata/sales-ui.as" in main.ts, and in the server's entry). For a type used by one screen only, a copy keeps the generated one as it is and does not warn:

atscript
export annotate Order as OrderForm {
    @meta.label 'Ordered on'
    OrderDate
}

A copy that annotates properties, like this one, goes into the copies of the host's registration or space, so it follows the live Order.

Annotation syntax and the rules of blocks are in Atscript's documentation.

See it live

The column widths, form grid and custom cells of Coffees in the browser app are annotate blocks. Code: src/model/roastery.ui.as.

Without a build step ​

A browser registration without model and types reads the $metadata at runtime and builds the types in memory (see Browser Client). The types built at runtime are the same as the compiled ones, but they cannot be imported, and the app waits for the document at start. buildServiceTypes(model, { service }) of @atscript/odata builds them from a model at hand, for a tool or a host of your own.

DOs and DON'Ts ​

  • Commit the saved $metadata (and its value-help folder and manifest) — don't make a build depend on reaching the service.
  • Regenerate by replacing the metadata file — don't edit the generated .as file or model module.
  • Limit a browser app to the entity sets it shows with entitySets — don't ship the model of a whole service for two screens.
  • Read the trailer after each metadata change — don't assume every value list or property made it into the types.
  • Keep dbPlugin() and uiPlugin() in the config — the generated file does not compile without them.
  • Set language for every service (or fetch with --language) — without it the labels follow whoever is signed in.
  • Fetch again when the service changed (a Moost server's drift report says so; the browser says nothing) — the app runs on the live $metadata, but your code is typed against the saved file.

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.