Skip to content

Worked Example ​

A small bookshop, as an SAP CAP app would start it, taken through the path: its .cds model and service, the same screen over the SAP CAP service, then the Atscript model, its controllers and the same screen over Atscript DB.

The SAP CAP app ​

cds
// db/schema.cds
namespace my.bookshop;
using { cuid, managed } from '@sap/cds/common';

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

entity Authors : cuid {
  name  : String(111) @mandatory;
  books : Association to many Books on books.author = $self;
}
cds
// srv/cat-service.cds
using my.bookshop as my from '../db/schema';

service CatalogService {
  entity Books as projection on my.Books;
  @readonly entity Authors as projection on my.Authors;
}

annotate CatalogService.Books with {
  title  @title: 'Title';
  stock  @title: 'Stock';
  price  @title: 'Price';
  author @title: 'Author';
}
js
// srv/cat-service.js
const cds = require("@sap/cds");

module.exports = cds.service.impl(function () {
  this.before("CREATE", "Books", (req) => {
    if (req.data.stock > 0 && req.data.price == null) {
      req.reject(400, "A book in stock needs a price", "price");
    }
  });
});

Step 1: the screen over the SAP CAP service ​

Save the $metadata and generate:

bash
npx atscript-odata fetch 'http://localhost:4004/odata/v4/catalog/$metadata' \
  --out src/odata/catalog.xml --language en
ts
// atscript.config.ts (plugins)
odataPlugin({ services: [{ name: "catalog", metadata: "odata/catalog.xml" }] }),

The Moost server serves the two entity sets through OData controllers, at the URLs the screen will keep:

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 catalog from "../src/odata/catalog.as";
import { model } from "../src/odata/catalog.model.gen";

// The SAP CAP service is called as one technical user; the server signs in its own users.
const space = createODataSpace({
  baseUrl: "http://localhost:4004/odata/v4/catalog",
  model,
  types: catalog,
  init: basicAuth({ user: process.env.CATALOG_USER!, password: process.env.CATALOG_PASSWORD! }),
});
provideDbSpace(space, "catalog"); // the service name, the types' @db.space

@TableController(catalog.Books, "api/catalog/Books")
export class BooksController extends ODataTableController<typeof catalog.Books> {}

@ReadableController(catalog.Authors, "api/catalog/Authors")
export class AuthorsController extends ODataReadableController<typeof catalog.Authors> {}

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(BooksController, AuthorsController);
await app.init();

The screen is the one of the Quick Start, given the entity set's URL:

vue
<!-- src/BooksPage.vue -->
<template>
  <EntityScreen url="/api/catalog/Books" />
</template>

It lists the books with their labels, filters and sorts them, and creates a book with a form. The form validates the title's length, does not demand the ID (SAP CAP generates it for a cuid key), and offers a picker over the authors, because the association is a relation whose target has a controller. SAP CAP still checks @mandatory, @assert.range and the handler: when it refuses a book, its message lands on the field it names.

Step 2: the Atscript model ​

The same entities as an .as model:

atscript
// src/models/bookshop.as
@db.table 'books'
@meta.label 'Book'
export interface Book {
    @meta.id
    @db.default.uuid
    ID: string.uuid

    @meta.label 'Title'
    @meta.required
    @expect.maxLength 111
    title: string

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

    @meta.label 'Price'
    @db.column.precision 9, 2
    price?: decimal

    @meta.label 'Author'
    @db.rel.FK
    author_ID?: Author.ID

    @db.rel.to
    author?: Author

    @meta.label 'Created'
    createdAt?: number.timestamp.created

    @meta.label 'Changed'
    modifiedAt?: number.timestamp.updated

    @db.column.version
    version: number
}

@db.table 'authors'
@meta.label 'Author'
export interface Author {
    @meta.id
    @db.default.uuid
    ID: string.uuid

    @meta.label 'Name'
    @meta.required
    @expect.maxLength 111
    name: string

    @db.rel.from
    books?: Book[]
}

Line by line, against the .cds model:

SAP CAPAtscript
entity Books : cuid@db.table 'books', ID with @meta.id and @db.default.uuid
managed (createdAt, modifiedAt)number.timestamp.created, number.timestamp.updated
title : String(111) @mandatory@meta.required, @expect.maxLength 111
stock : Integer @assert.range: [0, 9999]number.int with @expect.min 0, @expect.max 9999
price : Decimal(9,2)decimal with @db.column.precision 9, 2
author : Association to Authorsauthor_ID with @db.rel.FK, author with @db.rel.to
books : Association to many Books on …books with @db.rel.from
@title: 'Title'@meta.label 'Title'
(optimistic concurrency)version with @db.column.version

The validation now runs in the browser (the form, db-client's preflight) and on the server (every write), from the same annotations. Create the tables with npx asc db sync against the database of the Atscript config (see Move the Services).

Step 2: the controllers ​

The same URLs, now served by Atscript DB on PostgreSQL. The handler becomes onWrite:

ts
// server/main.ts
import { DbSpace, type TDbWriteAction } from "@atscript/db";
import { PgDriver, PostgresAdapter } from "@atscript/db-postgres";
import {
  AsDbController,
  AsDbReadableController,
  ReadableController,
  TableController,
} from "@atscript/moost-db";
import { HttpError, MoostHttp } from "@moostjs/event-http";
import { Moost } from "moost";
import { Author, Book } from "../src/models/bookshop.as";

const driver = new PgDriver({ connectionString: process.env.DATABASE_URL });
const db = new DbSpace(() => new PostgresAdapter(driver));

@TableController(db.getTable(Book), "api/catalog/Books")
export class BooksController extends AsDbController<typeof Book> {
  protected override onWrite(action: TDbWriteAction, data: unknown) {
    const book = data as { stock?: number; price?: string };
    if (action === "insert" && (book.stock ?? 0) > 0 && book.price == null) {
      return new HttpError(400, "A book in stock needs a price");
    }
    return data;
  }
}

@ReadableController(db.getTable(Author), "api/catalog/Authors")
export class AuthorsController extends AsDbReadableController<typeof Author> {}

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

@readonly entity Authors becomes a readable controller: no write endpoints. Authorization (@requires, @restrict) would go onto these classes with Aooth.

Step 2: the screen ​

vue
<template>
  <EntityScreen url="/api/catalog/Books" />
</template>

Unchanged. The URL is the same, and /meta now describes the Atscript DB table. The form gains what the new model says: the required title and the range of stock are checked before any request, and the version field lets an edit form detect a concurrent change. The handler's rule answers 400 with its message.

Step 3 ​

The bookshop no longer needs SAP CAP: remove the .cds files, @sap/cds and the OData plugin entry for catalog, and deploy the Node.js server with its database wherever you like. The checklist is in Drop the SAP CAP runtime.

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.