Skip to content

1. A browser app served by SAP CAP ​

Your SAP® CAP service stays as it is. You add a Vue page made with Atscript UI, typed from the service's $metadata. The page talks OData to the service, and SAP CAP serves the page, so both share one origin.

text
 browser ──OData /odata/v4/catalog──► SAP CAP ──► database
    ▲                                   │
    └──────── the page, from app/ ──────┘

The code: 1_atscript_spa, an SAP CAP project as usual (db/, srv/) plus the page in src/.

Running the browser app ​

bash
cd 1_atscript_spa
pnpm dev       # SAP CAP on :4004, and Vite on :5173, which passes /odata on to SAP CAP
pnpm build     # the page, into app/
pnpm start     # SAP CAP, serving the page and the service at :4004

SAP CAP keeps the data in memory and loads db/data/*.csv on each start.

Generating the types from SAP CAP's $metadata ​

The types come from the running service. Save its $metadata once and commit it; the Atscript plugin turns it into types on every build. With SAP CAP running, pnpm generate saves it (package.json):

bash
atscript-odata fetch http://localhost:${PORT:-4004}/odata/v4/catalog --out src/generated/catalog.xml --language en

The command fills in ${PORT:-4004} itself, in any shell, so it finds SAP CAP where pnpm dev started it. A service with a login takes --user and --password, or --header (Save the $metadata). atscript.config.ts registers the file:

ts
odataPlugin({ services: [{ name: "catalog", metadata: "generated/catalog.xml" }] }),

Each build writes src/generated/catalog.as and catalog.model.gen.ts. Never edit them: after a change to the service, run pnpm generate again. See Generating Models.

What the generated types carry ​

SAP CAP writes most of your .cds model into the $metadata. The books in db/schema.cds, with @title labels and @cds.odata.valuelist from srv/cat-service.cds:

cds
entity Books : cuid, managed {
  title    : String(111)  @mandatory;
  stock    : Integer      default 0 @assert.range: [0, 9999];
  price    : Decimal(9, 2) @mandatory;
  currency : String(3)    default 'EUR';
  author   : Association to Authors;
  genre    : Association to Genres;
}

become, in catalog.as:

atscript
export interface Books {
    // …
    @meta.label 'Title'
    @meta.required
    @expect.maxLength 111
    @ui.dict.label
    title: string

    @meta.label 'Stock'
    @meta.default '0'
    @expect.min 0
    @expect.max 9999
    stock?: number.int.int32

    // …
    @meta.label 'Genre'
    @expect.maxLength 3
    @ui.valueHelp Genres, 'code'
    @ui.valueHelp.column 'code'
    @ui.valueHelp.column 'name'
    @ui.type 'select'
    @db.rel.FK
    genre_code?: Genres.code
    // …
}

So the form shows the labels, starts with the defaults, asks for the title and the price (@mandatory), checks the stock's range, and offers an author picker and a genre dropdown (ValueListWithFixedValues). cuid lets a new book leave out its ID, and @odata.etag refuses a save over someone else's change.

The names of the author and the genre come from SAP CAP's usual texts, read through the association. The book's own key has a text too, its title:

cds
ID         @title: 'ID'     @Common.Text: title;
// …
author     @title: 'Author' @Common: { Text: author.name, TextArrangement: #TextOnly };
genre      @title: 'Genre'  @Common: { Text: genre.name, TextArrangement: #TextOnly, ValueListWithFixedValues };

The generator makes name the dictionary label of Authors and Genres (@ui.dict.label 'text'), so Atscript UI shows a name wherever a code shows: in the table, the filter chips and the form. It reads the names of the codes on the screen with one lookup per dictionary and page. See Texts through a navigation.

The book's text, ID @Common.Text: title, makes title the dictionary label of Books (@ui.dict.label on title, and @ui.valueLabel 'title' on ID). So an action names the books it runs on by their titles: the Restock dialog shows the title, then the book's key, Persuasion (b7e2d4a0-5c1f-4e8b-8a10-000000000003). See Dictionary labels.

Everything the generator reads from an SAP CAP service
In your .cds modelIn the generated .as
entities exposed by the serviceone interface per entity set, with @db.table
key elements@meta.id
cuid keys@db.default.uuid: a create may leave the key out
@title, @Common.Label@meta.label
@description, doc comments@meta.description, unless there is a quick info (@Common.QuickInfo)
String(n), Decimal(p,s)@expect.maxLength, @db.column.precision
@mandatorya required field (no ?); a text also @meta.required
@assert.range on an integer or Double@expect.min, @expect.max
@assert.range on a Decimal or Int64listed in the trailer: Atscript checks the bounds of numbers only
@Common.IsDigitSequence@expect.pattern '^\d*$' on a text: digits only, or empty
@UI.MultiLineText@ui.form.type 'textarea': a multi-line input in the form
@readonly elements, @Core.Computed@meta.readonly, with @db.default.store on a scalar
managed (createdAt, createdBy, …)read-only fields the service fills (@meta.readonly, @db.default.store); createdBy and modifiedBy also get @meta.description "User's unique ID", from SAP CAP's User type
@Common.ValueList@ui.valueHelp with fills and columns (Value Helps)
@Common.Text with @UI.TextArrangement@ui.valueLabel; the text of a single key, or a foreign key's through its association (author.name): @ui.dict.label on the target (Value Helps)
associations and compositionsrelations, loaded with $with (Relations)
@odata.etagthe version token __etag (Writes)

The file ends with what the types couldn't express (the trailer). An SAP CAP service gets the standard dialect by itself.

SAP CAP's rules still run on every save ​

SAP CAP still checks every save and runs your handlers, such as the bookshop's "one title per author" in srv/cat-service.js:

js
this.before(["CREATE", "UPDATE"], Books, async (req) => {
  // …
  if (twin && twin.ID !== book.ID)
    req.error(400, "This author already has a book with this title", "title");
});

The form shows the message under the field it names (Messages by field).

Your own UI hints over the generated types ​

The generated file is overwritten, so your hints go into annotate blocks in src/models/catalog.ui.as:

atscript
annotate Books {
    // …
    @ui.table.width '28ch'
    title

    @expect.message 'Enter a price' // a missing price in plain words: SAP CAP's @mandatory made it required
    price
}

SAP Fiori® elements annotations (@UI.LineItem, …) aren't read: you lay out the screens here. src/api.ts imports this file before the types are used (Enrich the generated types).

SAP CAP serving the page from app/ ​

SAP CAP's server serves the app/ folder at its root (server.js: "defaults to ./app"), so the build goes there (vite.config.ts):

ts
build: { outDir: "app", emptyOutDir: true },

The page and /odata/v4/catalog then share one origin: no proxy, no CORS. Hash routes (#/books) need no fallback on the server. Behind an approuter or a reverse proxy, keep page and service on one origin the same way (Reaching the service).

Proxying /odata to SAP CAP in development ​

In development, Vite passes /odata on to SAP CAP:

ts
server: { port: Number(DEV_PORT), proxy: { "/odata": `http://localhost:${PORT}` } },

Building the screens over the OData service ​

src/api.ts is the only file that knows where the data is:

ts
export const odata = createODataClientFactory({
  services: [{ baseUrl: "/odata/v4/catalog", model, types: catalog }],
});
setDefaultClientFactory(odata);

/** Reads the live $metadata before the first screen renders: the generated types follow the running service. */
export const connect = () => odata.connect();

/** The screens' entity sets. Each URL names a set; a table or a form reads its columns, fields and actions from it. */
export const urls = { books: odata.urlOf(catalog.Books), authors: odata.urlOf(catalog.Authors) };

The screens only take a URL. The books table in BooksScreen.vue is <AsTableRoot :url="urls.books" …>, and BookForm.vue builds the form from the same URL's metadata, after Atscript UI's form example.

Keep the URLs in one file

In step 2 only src/api.ts changes on the page (What changes on the page). Going straight to step 3 works too: the browser client's fallback gives every URL that isn't OData a plain Atscript DB client (How URLs are routed).

The restock action from SAP CAP's service ​

SAP CAP declares a bound action in srv/cat-service.cds and handles it in srv/cat-service.js:

cds
action restock(quantity : Integer @title: 'Quantity' @mandatory @assert.range: [1, 999]) returns Books;

The page has no code for it. The browser client reads the action from the live $metadata, and Atscript UI shows a Restock button on each row, with a form built from the generated BooksRestockParams. The dialog names the book by its title, Emma (b7e2d4a0-…), since title is the dictionary label of Books. In your own code, the generated handle types the call:

ts
odata.call(ops.Books.restock, { row, params: { quantity: 5 } });

See Operations in the browser.

Signing in: each user's own login ​

The example asks for no login. With one, the browser's session is the login: users sign in to SAP CAP or its approuter, every call carries that session, and SAP CAP authorizes each user as before. See Credentials and Sessions.

What the browser app doesn't cover ​

  • Drafts. Draft-enabled entities are read-only for now: keep editing them in your existing app (Limitations).
  • Your SAP Fiori apps keep working next to the new page, against the same service.

Next: 2. A Moost server in front of SAP CAP.

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.