@atscript/odata/plugin and CLI
Complete export reference for the @atscript/odata/plugin subpath and the atscript-odata command line tool. See Generating models for the narrative.
pnpm add @atscript/odata @atscript/core @atscript/typescript @atscript/db @atscript/ui @uniqu/core
pnpm add -D unplugin-atscriptThe ./plugin subpath is Node-only (it reads and writes files). The main entry @atscript/odata is documented on its own page. The plugin is both the default export and the named export odataPlugin.
CLI: atscript-odata fetch
Saves the $metadata of a service, every value-help document it references (OData v4 Common.ValueListReferences) and the manifest the plugin reads.
atscript-odata fetch <$metadata URL> --out <file> [options]| Flag | Meaning |
|---|---|
--out <file> | Where to save the $metadata, for example src/odata/sales.xml. Required. |
--user <name> | Basic authentication user. Default: $ODATA_USER. Ignored when a --header sets Authorization. |
--password <secret> | Basic authentication password. Default: $ODATA_PASSWORD. Required once a user is set. |
--header "Name: value" | A header for every call. Repeatable. An Authorization header here wins over basic authentication. |
--query name=value | A query option for every call, for example sap-client=100. Repeatable. Options in the URL count too. |
--language <code> | Reads every document in this language (sap-language and Accept-Language), for example EN, and writes it to the manifest, where the plugin takes it as the service's language. Without it the command says so in its output. |
--help | Prints the usage text. |
| Exit code | Meaning |
|---|---|
0 | Everything was saved. |
1 | Something could not be read: the $metadata (nothing written) or a value-help document (the rest saved). |
2 | Usage error: missing --out, malformed --header / --query, a user without a password. |
ODATA_USER=me ODATA_PASSWORD=secret npx atscript-odata fetch \
'https://host/sap/opu/odata/sap/ZDEMO_ORDERS_SRV/$metadata' \
--out src/odata/sales.xml --query sap-client=100 --language ENFiles written next to --out: the $metadata itself (sales.xml), the folder sales.value-helps/ with one document per reference (<service>.<property>.xml), and the manifest sales.value-helps.json when it lists a value-help document or a language ({ "language": "EN", "valueHelps": { … } }). A file is rewritten only when its content changes, so running the command again is safe. The function behind the command is fetchODataMetadata.
Functions
odataPlugin
const odataPlugin: (options?: TODataPluginOptions) => TAtscriptPlugin;
export default odataPlugin;The Atscript plugin. It declares the @odata.* annotations and, in the buildStart hook of every asc run, build() call and bundler build (watch rebuilds and dev server starts included), generates one .as file and one model module per configured service from its saved $metadata, and the controllers module of a service that asks for one (controllers). The model module records what it was built from (model.build: the name, entitySets, operations, language and the digests of the saved documents), which the hosts compare the live documents with (see ServiceModelBuild). A missing or unreadable metadata file, an unreadable manifest, an unknown entity set, an operations.exclude or controllers.writable name the service lacks, or controllers without the model module fails the build; a missing value-help document does not. The editor's language server does not run the hook: it reads what the last build wrote. Keep dbPlugin() and uiPlugin() in the same config, since the generated types use their annotations.
// 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" }] }),
],
});See Generating models for what is generated and when.
Operations. Every function import, function and action the selection holds gets an interface <Name>Params at the end of the .as file, a plain Atscript interface: the operation's label as @meta.label, and its parameters as fields, as entity properties are (@meta.label, @expect.maxLength, @db.column.precision, primitive tags, ? when a parameter is nullable or Core.OptionalParameter). For an operation called on rows, the parameters the row's key fills are left out. <Name> is the import name; for a bound OData v4 operation, the interface name of its entity type and its local name (OrderRelease). The operation's facts (whether a row can take it, how several rows are grouped) stay in the model module's model (OperationModel.available, .grouping), where the hosts take them from. Draft lifecycle operations are never generated, and neither is one the service marks never available. An operation whose types fall outside the selected entity sets, or that the engine cannot call, is left out and listed in skipped (kind operation); so is an availability path no row can be checked by. The selection rule is selectOperations.
@meta.label 'Release'
export interface ReleaseOrderParams {
@meta.label 'Note'
@expect.maxLength 40
Note?: string
}
export interface RecalcPricesParams {}The model module also exports ops: a typed handle (ODataOperationRef) per operation, unbound ones by import name, bound ones under their entity set by local name. Each names its form (paramsType), the declaration of the .as module a host finds it by. The types are imported type-only, as a namespace, so the module still loads nothing but the model, and the model's parse is marked pure.
// sales.model.gen.ts (generated)
import type * as T from "./sales.as";
export const ops = {
RecalcPrices: {
service: "sales",
operation: "RecalcPrices",
paramsType: "RecalcPricesParams",
} as ODataOperationRef<T.RecalcPricesParams, void>,
OrderSet: {
ReleaseOrder: {
service: "sales",
operation: "ReleaseOrder",
entitySet: "OrderSet",
paramsType: "ReleaseOrderParams",
} as ODataOperationRef<T.ReleaseOrderParams, T.Order, Pick<T.Order, "OrderId" | "__etag">>,
},
};generateODataModels
function generateODataModels(
options: TODataGenerateOptions,
cache?: TODataGenerationCache,
): TODataGenerationResult[];What the plugin runs: generates the .as file and the model module of every configured service, writing a file only when its content changes. With a cache, a service whose metadata file has not changed since the cache last saw it is not read again. Call it yourself to generate outside an Atscript build (a script, a test); relative paths need root.
fetchODataMetadata
function fetchODataMetadata(options: TODataFetchOptions): Promise<TODataFetchResult>;Saves a service's $metadata with every value-help document it references and the manifest, as atscript-odata fetch does. The documents are read as the hosts read them: each at its reference resolved against the $metadata URL, all at once, with the same headers and query options, in language when one is given. A value-help document that cannot be read is listed in failed; the one an earlier fetch saved for it stays. Throws ODataError when the $metadata cannot be read (nothing is written then), and the parser's Error when the answer is not an EDMX document.
import { fetchODataMetadata } from "@atscript/odata/plugin";
const result = await fetchODataMetadata({
url: "https://host/sap/opu/odata/sap/ZDEMO_ORDERS_SRV/$metadata",
out: "src/odata/sales.xml",
headers: { Authorization: `Basic ${btoa("me:secret")}` },
query: { "sap-client": "100" },
language: "EN",
});
for (const { reference, error } of result.failed) console.warn(reference, error);odataAnnotations
function odataAnnotations(): TAnnotationsTree;The @odata.* annotation specs as the tree an Atscript config takes under annotations. odataPlugin declares them already; use this only to declare the annotations without the plugin (for example in a config that compiles generated files someone else produced). The annotations are listed at ODATA_ANNOTATIONS.
Types
TODataPluginOptions
interface TODataPluginOptions {
/** Absolute directory relative service paths are taken from, instead of the Atscript rootDir. */
root?: string;
/** The services to generate models for. */
services?: TODataPluginService[];
}Set root (for example import.meta.dirname) when the metadata lives outside rootDir. A relative rootDir itself resolves against the folder of the config file in every host (asc, the bundler, the editor).
TODataPluginService
interface TODataPluginService {
/** Name of the service in your app; written as @db.space (the space a Moost server registers). Not "default". */
name: string;
/** Path of the saved $metadata (EDMX). */
metadata: string;
/** Path of the generated .as file. Default: `metadata` with the extension `.as`. Keep it inside rootDir. */
output?: string;
/** Generate only these entity sets and what their interfaces reference. Default: all. */
entitySets?: string[];
/** Path of the model module, or false for none. Default: `<output name>.model.gen.ts` beside the .as file. */
model?: string | false;
/** Saved value-help documents: reference URL as the $metadata writes it → path. Wins over the manifest. */
valueHelps?: Record<string, string>;
/** The language the $metadata and its value-help documents were saved in. Default: the manifest's. */
language?: string;
/** Operations to leave out: their import, local or qualified names. Drafts are always left out. */
operations?: { exclude?: string[] };
/** Also write the controllers module of a Moost server. Needs the model module. Default: off. */
controllers?: boolean | { output?: string; writable?: string[] };
}Relative paths are taken from the Atscript rootDir, or from the plugin's root.
language is the language the saved documents are in, as the service takes it: an SAP language code (EN, DE) or a language tag (en). It is written into model.build, and every metadata read of the hosts asks for it (sap-language and Accept-Language), so the labels stay in this language and the saved documents match the live ones. Default: the one atscript-odata fetch --language wrote to the manifest. Without one, the live documents come in whatever language the service picks for each caller, and the generated .as ends with a note saying so. Set it, also for a file saved from a signed-in browser (the browser's language); a service that is not SAP ignores sap-language. See The language. The manifest written by atscript-odata fetch beside metadata (sales.xml → sales.value-helps.json) is read by itself; valueHelps is needed only for documents saved by hand. See Value helps.
operations.exclude leaves operations out of the .as types, the ops handles, the controllers module and the model module's model, by import, local or qualified name; it is recorded in model.build, so the hosts select the same on the live service. A name the service does not have fails the build.
controllers writes the controllers module of a Moost server beside the .as file (<output name>.controllers.gen.ts, or controllers.output), in the same build and under the same cache stamp as the model module: a base per entity set with operations bound to its type, their Moost DB db actions, and the service's operations base, one POST route per unbound operation (see Operations and printControllersModule). Every base extends ODataReadableController, but those of the sets controllers.writable names, which extend ODataTableController. controllers with model: false, and a writable name the service does not have, fail the build. A service without operations gets a module that exports nothing.
TODataGenerateOptions
interface TODataGenerateOptions {
/** Absolute directory relative paths are taken from. Required unless every path is absolute. */
root?: string;
services?: TODataPluginService[];
}TODataGenerationResult
interface TODataGenerationResult {
service: string;
/** Absolute path of the metadata document. */
metadata: string;
/** Absolute path of the generated .as file. */
output: string;
/** false when the file already held the same content. */
written: boolean;
/** The model module, unless switched off. */
model?: { output: string; written: boolean };
/** The controllers module, with `controllers`. */
controllers?: {
output: string;
written: boolean;
/** Every db action of the set bases. */
actions: { entitySet: string; route: string; operation: string; level: "rows" | "table" }[];
/** Every route of the operations base. */
operations: { route: string; operation: string }[];
};
/** What the generated types do not express (also listed at the end of the .as file). */
skipped: SkippedItem[];
/** What the metadata parser tolerated instead of failing on. */
warnings: ParseWarning[];
}controllers lists every db action (route below the controller's prefix: actions/<Name>; operation as the engine calls it) and every route of the operations base, so a regeneration that adds one shows. SkippedItem and ParseWarning are exported by the main entry: see @atscript/odata. An operation left out is a SkippedItem of kind operation, where naming it (on v4 a bound one with its binding, Ns.Release(Ns.Order)).
TODataGenerationCache
type TODataGenerationCache = Map<string, { stamp: string; result: TODataGenerationResult }>;Remembers, per output file, the metadata it was last generated from. Pass the same map to repeated generateODataModels calls.
TODataFetchOptions
interface TODataFetchOptions extends Omit<ODataServiceTransportOptions, "baseUrl"> {
/** URL of the $metadata, or of the service root. Its query goes with every call. */
url: string;
/** File the $metadata is saved to, relative to the working directory. */
out: string;
/** Read every document in this language and write it to the manifest. */
language?: string;
signal?: AbortSignal;
}Takes every transport option of the service engine except baseUrl: headers, query, fetch, dialect and the rest (see ODataServiceTransportOptions). A query entry wins over an option of the same name in url. language is sent as sap-language and Accept-Language with every read, and written to the manifest, where the plugin takes it as the service's language.
TODataFetchResult
interface TODataFetchResult {
/** The saved $metadata (absolute path). */
metadata: string;
/** The manifest, when it lists a value-help document or a language. */
manifest?: string;
/** The saved value-help documents, by reference, in manifest order. */
valueHelps: { reference: string; file: string }[];
/** References that could not be read; `kept` names the document an earlier fetch saved. */
failed: { reference: string; error: string; kept?: string }[];
/** Documents of an earlier fetch the service no longer references, removed. */
removed: string[];
}TODataValueHelpManifest
interface TODataValueHelpManifest {
/** The language the documents were read in (--language), when one was asked for. */
language?: string;
/** Reference URL as the $metadata writes it → document, relative to the manifest's directory. */
valueHelps: Record<string, string>;
}The shape of the <name>.value-helps.json file atscript-odata fetch writes. The plugin reads it beside the metadata file and takes its language when the service has no language option; an unreadable or malformed manifest fails the build.