Skip to content

Quick Start ​

This page takes one OData service from its $metadata to a working screen: a table with filters and a create form with a value help. It shows the screen twice, once with the browser client talking OData directly and once behind a Moost server. Steps 1 to 3 are the same for both.

The app is typed at build time and live at runtime: the saved $metadata gives the models and their TypeScript types, and at runtime the host reads the service's live $metadata and runs on it (see Live Metadata).

The service is a synthetic SAP Gateway® v2 service, ZDEMO_ORDERS_SRV, with sales orders (OrderSet), their items (OrderItemSet) and customers (CustomerSet). Any OData v2 or v4 service works the same way.

Prerequisites

A Vue 3 + Vite app with Atscript UI set up as its quick start describes, and the packages of Installation.

1. Save the $metadata ​

Open the service's $metadata in a browser where you are signed in, and save the page as src/odata/sales.xml:

text
https://my-gateway.example.com/sap/opu/odata/sap/ZDEMO_ORDERS_SRV/$metadata?sap-client=100&sap-language=EN

One file holds the whole service: every entity set, navigation and value list. This works behind single sign-on, where a script cannot log in. Note the language the labels came in (sap-language above, else the language you are signed in with): step 2 names it.

When the service accepts basic authentication (or a header you pass, such as a session cookie), the CLI saves it for you, in the language you name:

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

For an OData v4 service that keeps its value lists in separate value-help services (as RAP does), the CLI also saves those documents and a manifest next to the file. Saved by hand, they go in the plugin's valueHelps option. Run the CLI again to refresh; unchanged files stay as they are. Its options are listed in the API reference.

2. Add 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({
      // language: the file was saved from a browser (with the CLI's --language, leave it out)
      services: [{ name: "sales", metadata: "odata/sales.xml", language: "EN" }],
    }),
  ],
});

name is how your app calls the service; metadata is relative to rootDir; language is the language the file was saved in, which the hosts ask for when they read the live $metadata. The example names it for a file saved from a browser (step 1, sap-language=EN). A file the CLI saved needs no language: the CLI wrote its --language next to the file. The generated types use @db.* and @ui.* annotations, so dbPlugin() and uiPlugin() stay in the list.

3. Generate ​

bash
npx asc -f dts

Every asc run and every bundler build (dev server start included) regenerates before it compiles. Two files appear next to sales.xml.

src/odata/sales.as: one interface per entity set. Abridged:

atscript
// Generated by @atscript/odata from the $metadata of the OData v2 service 'sales'.
// Do not edit: the file is overwritten when the metadata changes.
// To add labels, validation or UI hints, enrich these types with `annotate` blocks in your own .as files.

@db.table 'OrderSet'
@db.space 'sales'
@meta.label 'Sales Order'
export interface Order {
    @meta.id
    @meta.label 'Order'
    @meta.readonly
    @db.default.store
    @normalize.uppercase
    OrderId: string

    @meta.label 'Customer'
    @expect.maxLength 10
    @ui.valueHelp Customer, 'CustomerId', `Country = Order.Country`
    @ui.valueHelp.fill 'CustomerName', 'CustomerName'
    @ui.valueHelp.column 'CustomerId'
    @ui.valueHelp.column 'CustomerName'
    @ui.valueLabel 'CustomerName'
    CustomerId: string

    @meta.label 'Customer Name'
    @meta.readonly
    @db.default.store
    CustomerName?: string

    @meta.label 'Net Amount'
    @db.column.precision 15, 2
    @db.amount.currency.ref 'Currency'
    NetAmount?: decimal

    @db.column.version
    @db.column.version.token
    __etag: string

    @meta.label 'Items'
    @db.rel.from
    Items?: OrderItem[]

    // … more properties
}

// … OrderItem, Customer

// Not expressed in these types (3):
// - ZDEMO_ORDERS_SRV.Order/CustomerId: value list "Domestic" (only the first value list of a property is bound)
// - ZDEMO_ORDERS_SRV.Order/Status: value list (its mapping is in a separate annotation document)
// - ZDEMO_ORDERS_SRV.Order/Currency: value list (its mapping is in a separate annotation document)

@db.table is the entity set; @db.space is the service's name, which a Moost server registers its space under (step 5b). The key the service assigns is read-only and not required on create (@db.default.store). The customer field opens a picker over CustomerSet, narrowed by the order's country, and a pick fills the customer's name: @ui.valueHelp.fill 'CustomerName', 'CustomerName' writes the picked customer's CustomerName into the order's own CustomerName (see Filling other fields). The service declares optimistic concurrency, so the type carries a version token, __etag. The comment block at the end lists what the service declares and the types cannot express. Generating Models explains each mapping.

src/odata/sales.model.gen.ts: the service model the runtime works from, and a record of what it was built from (model.build), which the hosts compare the live $metadata with:

ts
import type { ServiceModel } from "@atscript/odata";

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

Do not edit either file. Labels, validation and UI hints of your own go into annotate blocks in your own .as files (see Enrich the generated types).

4. The screen ​

One component serves both paths: it takes the URL of the entity set, renders a table, and builds a create form from the entity set's metadata. Atscript UI asks its client factory for a client per URL; which client answers is decided in step 5.

vue
<!-- src/EntityScreen.vue -->
<script setup lang="ts">
import { deserializeServedType, getDefaultClientFactory, type FormDef } from "@atscript/ui";
import { AsForm, createAsFormDef, createDefaultTypes } from "@atscript/vue-form";
import { AsFilters, AsTable, AsTableRoot, createDefaultCellTypes } from "@atscript/vue-table";
import { ref, shallowRef } from "vue";

const props = defineProps<{ url: string }>();

const cellTypes = createDefaultCellTypes();
const formTypes = createDefaultTypes();
const client = getDefaultClientFactory()(props.url);

const form = shallowRef<{ def: FormDef; formData: { value: unknown } }>();
const listVersion = ref(0);

async function openCreate() {
  // The type as served for this URL: in the browser client it carries the URL of
  // every value-help target, behind a Moost server its /meta does.
  const meta = await client.meta();
  form.value = createAsFormDef(deserializeServedType(meta.type), undefined, {
    metaFields: meta.fields,
    versionColumn: meta.versionColumn, // the version token is no form field
    mode: "create",
  });
}

async function create(data: unknown) {
  await client.insert(data as Record<string, unknown>);
  form.value = undefined;
  listVersion.value++; // mount the table again: it reads the new row
}
</script>

<template>
  <AsTableRoot :key="listVersion" :url="url" :types="cellTypes" :limit="20">
    <AsFilters />
    <AsTable />
  </AsTableRoot>

  <button type="button" @click="openCreate">New</button>
  <AsForm
    v-if="form"
    :def="form.def"
    :form-data="form.formData"
    :types="formTypes"
    @submit="create"
  />
</template>

The table shows the labels, sorts and filters what the service lets it, and pages with the service's count. The form shows OrderId read-only and does not demand it (the service assigns it), offers the customer picker, and validates the lengths the service declares. A refusal of the service comes back as a ClientError whose entries name the fields; Errors shows how to put them on the form.

See it live

Filter Orders in the browser app: the URL keeps the filters, so a filtered list is a link. Code: ListScreen.vue (the table and its URL query) and TableToolbar.vue (the filter bar).

5a. Browser client ​

Register the service with a client factory, and mount the app once the factory has read the live $metadata:

ts
// 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.

vue
<EntityScreen url="/odata/sales/OrderSet" />

The URL /odata/<service>/<EntitySet> is how Atscript UI addresses the entity set; it is never fetched. The client calls the service at baseUrl, which must be reachable from the page's origin. In development, proxy it:

ts
// vite.config.ts
export default defineConfig({
  // … plugins
  server: {
    proxy: {
      "/sap": { target: "https://my-gateway.example.com", changeOrigin: true },
    },
  },
});

The browser's own session with the service carries the login: a user signed in to the system (or redirected through single sign-on) is the user the service sees. More in Browser Client.

5b. Moost Server ​

The browser needs nothing registered: Atscript UI's built-in factory gives every URL a plain Atscript DB client. The server declares one controller per entity set it serves, and reads the live $metadata before Moost creates them:

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! }),
});
provideDbSpace(space, "sales"); // the types' @db.space

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

// The target of the customer value help: a value help appears when its target is served.
@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();
vue
<EntityScreen url="/api/sales/OrderSet" />

provideDbSpace registers the space under the name the generated types carry as @db.space, so each controller binds by its model, as in any Moost DB app. Proxy /api to the server in development ("/api": "http://localhost:3000"). The server calls the service as a technical user, with the credentials in init, and keeps the session a write needs by itself; your server authenticates its own users (see Credentials and Sessions). The server imports .as files the same way the browser does, through unplugin-atscript in its build. More in Moost Server.

What you have now ​

  • Typed models of the service, regenerated by every build, and run on the live $metadata.
  • A table that sorts, filters, searches and pages the way the service allows, and refuses what it does not.
  • A form with the service's lengths, read-only fields and value help.
  • The same screen over OData directly or over your own server, chosen by one URL.

Next ​

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.