Moost Server App
The page talks only to its own Moost server, in Atscript DB's REST protocol. The server talks OData v4 to the service, as one technical user. Your rules and hooks sit on the server, and no OData code ships to the browser. Page and server are one Vite project.
Open the app · Source: atscript-odata-demo-moost
Run it
git clone https://github.com/moostjs/atscript-odata-demo-moost
cd atscript-odata-demo-moost
pnpm install
pnpm devVite serves the page and runs the Moost server in the same process, under /api. The server uses the public service. For a local service, or your own, put the settings in .env.local:
ODATA_URL=http://localhost:4010/odata/v4/roastery
# credentials for your own service; the Roastery service needs none
ODATA_USER=
ODATA_PASSWORD=The layout
atscript.config.ts plugins; the service and its controllers
vite.config.ts Vite, with Moost's plugin
src/
generated/ GENERATED: $metadata, types, controller bases
model/roastery.ui.as YOURS: annotate blocks
model/coffee-sales.as YOURS: the Ordered column
server/space.ts YOURS: the service as a DB space
server/controllers.ts YOURS: a controller per entity set
server/main.ts YOURS: connect, register, start
ui/api.ts YOURS: the page's clients and calls
ui/ YOURS: the screens
env.d.ts YOURS: declare type decimal = stringNever edit src/generated/: pnpm generate and the build write it. The server is src/server/, the page src/ui/; both read the generated types.
From $metadata to types and controllers
pnpm generate saves the $metadata as in the browser app. Here the service in atscript.config.ts also asks for controllers:
{
name: "roastery",
metadata: "generated/roastery.xml",
controllers: {
writable: ["Coffees", "Cafes", "Orders", "OrderItems"],
},
},So the build also writes roastery.controllers.gen.ts: CoffeesBase and OrdersBase with the bound actions as db actions, and RoasteryOperationsBase with the unbound operations as routes. See The controllers module.
The space
src/server/space.ts makes the service an Atscript DB space, each entity set a table:
export const space = createODataSpace({
baseUrl: ODATA_URL ?? "https://demo.odata.atscript.dev/…",
model,
types: roastery,
init: ODATA_USER ? basicAuth({ … }) : undefined,
});
provideDbSpace(space, "roastery");With ODATA_USER set, the server calls the service with basic auth, as ODATA_USER with ODATA_PASSWORD: the service sees that one user, never the people using the page. "roastery" is the @db.space the generated types carry. See The space and Credentials and Sessions.
The controllers
src/server/controllers.ts declares a controller per entity set the page writes. Coffees and Orders extend their generated bases, Cafés and OrderItems ODataTableController, and the unbound operations get one of their own:
@TableController(roastery.Order, "api/roastery/Orders")
export class OrdersController extends OrdersBase {}
@Inherit()
@Controller("api/roastery/ops")
export class OperationsController extends RoasteryOperationsBase {}The code lists the forms and filters pick from get read-only controllers from valueHelpControllers, in main.ts. See Moost Server and Value-help controllers.
A column the server adds
Ordered is not in the service: it is the kilograms of the coffee in every order's items. src/model/coffee-sales.as declares it:
export interface CoffeeSales {
@meta.label 'Ordered'
@db.unit 'kg'
@ui.table.width '11ch'
orderedKg?: number.int
}The Coffees controller fills it, with one aggregate() on OrderItems per page of rows:
@TableController(roastery.Coffee, "api/roastery/Coffees")
@DbDecorations(CoffeeSales, { requires: { orderedKg: ["ID"] } })
export class CoffeesController extends CoffeesBase {
protected override async decorateRows(
rows: Pick<roastery.Coffee & CoffeeSales, "ID" | "orderedKg">[],
ctx: TDbDecorateContext,
) {
if (!ctx.decorations.has("orderedKg") || rows.length === 0) return;
const ordered = await space.getTable(roastery.OrderItem).aggregate({
filter: { coffee_ID: { $in: rows.map((row) => row.ID) } },
controls: {
$groupBy: ["coffee_ID"],
$select: ["coffee_ID", { $fn: "sum", $field: "quantityKg", $as: "kg" }],
},
});
const kg = new Map(ordered.map((group) => [group.coffee_ID, Number(group.kg)]));
for (const row of rows) row.orderedKg = kg.get(row.ID) ?? 0;
}
}requires reads each row's ID whenever orderedKg is asked for. The server's aggregate() rows are untyped, hence Number(group.kg) (see Type Safety). See Your own base class and Atscript DB: declared decorations.
Startup
src/server/main.ts connects to the service first, trying for 30 seconds, then registers the controllers, then calls app.init(), which creates them:
app.registerControllers(
...own,
OperationsController,
...valueHelpControllers(space, { prefix: "api", own }),
);
await app.init();It also gives each visitor a request budget with Aooth's rate limits. See Connecting.
The page
src/ui/api.ts points Atscript UI at the server, and gives the screens typed clients and the operations routes:
setDefaultClientFactory((url, options) => new Client(url, { ...options, fetch: serviceFetch }));
/** An entity set's URL, from its type's @db.table: its controller on the server. */
export const urlOf = (type: TAtscriptAnnotatedType) =>
`/api/roastery/${type.metadata.get("db.table")}`;
/** An entity set's client, typed by its type. */
export const client = <T extends TAtscriptAnnotatedType>(type: T) =>
getDefaultClientFactory()<T>(urlOf(type));
/** The unbound operations, POST routes of the server's operations controller. */
export const roasteryOps = operationsClient("/api/roastery/ops", { fetch: serviceFetch });The Overview reads with client(roastery.Order).aggregate(…) and calls roasteryOps.call(ops.bestsellers, { weeks: 12, count: 5 }); the Receive beans… dialog calls roasteryOps.call(ops.receiveBeans, params). Both are checked against the generated types and handles, as in the browser app, and the page ships no OData code: operationsClient comes from @atscript/moost-odata/client, which is fetch only. The list screens take urlOf(screen.type), and the Coffees screen is a ListConfig<roastery.Coffee & CoffeeSales>, so its orderedKg column is checked too. The screens are otherwise the browser app's. See From a Moost page and Type Safety.
What the server adds
- All matching rows. On Orders, select every loaded row: the table offers all orders the filter matches, and the server runs the action on that query.
- Availability. Rows an action does not apply to, as the service says, are skipped and not sent.
- Columns of your own, such as Ordered on Coffees.
See What differs from the Moost server and Host differences.
On your own service
- Put its URL in the
generatescript ofpackage.json, and runpnpm generate. - Set
ODATA_URLto it, andODATA_USERandODATA_PASSWORDto the server's credentials. - List the entity sets the server writes in
writableofatscript.config.ts, and declare their controllers insrc/server/controllers.ts. - Write
annotateblocks and screens for its types.