Skip to main content

ApiDocument

ApiDocument is the root object of an OPRA application. It holds the type registry, linked external documents, and the API transport definition. Every field type, operation parameter, and response body is resolved through an ApiDocument instance.

Package: @opra/common


ApiDocumentFactory.createDocument()

Do not construct ApiDocument directly. Use the static factory method to build one asynchronously. The factory resolves all type references, validates the schema, and returns a fully initialised document.

static createDocument(
schemaOrUrl: string | ApiDocumentFactory.InitArguments,
options?: Partial<DocumentInitContext>,
): Promise<ApiDocument>
ParameterTypeDescription
schemaOrUrlstring | InitArgumentsInit object or a URL pointing to a remote OPRA schema JSON.
options.maxErrorsnumberMaximum number of schema errors to collect before aborting.
options.showErrorDetailsbooleanInclude error detail messages in the thrown OpraDocumentError.
import { ApiDocumentFactory } from '@opra/common';

// From an init object
const document = await ApiDocumentFactory.createDocument({
info: { title: 'Customer API', version: '1.0' },
types: [Customer, Address],
api: {
transport: 'http',
name: 'CustomerApi',
url: '/api',
controllers: [CustomersController],
},
});

// From a remote schema URL
const document = await ApiDocumentFactory.createDocument('https://api.example.com/opra.json');

Throws OpraDocumentError if the schema contains validation errors.


Init options

FieldTypeDescription
infoDocumentInfoHuman-readable metadata (title, version, description, contact, license).
typesDataTypeInitSourcesTypes to register at root level. Accepts a class, array of classes, or a record keyed by name.
referencesRecord<string, ReferenceThunk>Linked external documents keyed by namespace alias. Each value is a zero-argument async function returning an ApiDocument or init object.
apiHttpApi | MQApi | WSApiAPI transport configuration (transport: 'http' | 'mq' | 'ws').

Properties

PropertyTypeDescription
idstringMD5 fingerprint of the exported schema. Recomputed on every call to invalidate().
urlstring | undefinedCanonical URL of this document.
infoOpraSchema.DocumentInfoDocument metadata.
typesDataTypeMapRoot-level type registry.
referencesResponsiveMap<ApiDocument>Linked external documents keyed by namespace alias.
apiHttpApi | MQApi | WSApi | undefinedThe API transport definition.
httpApiHttpApi | undefinedShorthand getter — returns api if it is an HttpApi, otherwise undefined.
mqApiMQApi | undefinedShorthand getter — returns api if it is an MQApi, otherwise undefined.
wsApiWSApi | undefinedShorthand getter — returns api if it is a WSApi, otherwise undefined.

Type lookup

Type resolution is performed through document.node, which walks the document hierarchy from the current scope upward.

findDataType()

findDataType(nameOrCtor: string | Type | EnumObject, scope?: string): DataType | undefined

Returns the data type or undefined if not found.

getDataType()

getDataType(nameOrCtor: string | Type | EnumObject, scope?: string): DataType

Returns the data type or throws if not found.

Typed variants

getComplexType(nameOrCtor, scope?) // throws if not a ComplexType
getSimpleType(nameOrCtor, scope?) // throws if not a SimpleType
getEnumType(nameOrCtor, scope?) // throws if not an EnumType
getArrayType(nameOrCtor, scope?) // throws if not an ArrayType

All methods accept a string name, a constructor reference, or an enum object:

document.node.getDataType('Customer'); // by name
document.node.getDataType(Customer); // by constructor
document.node.getDataType(Gender); // by enum object

// Scoped lookup — resolves only if the type is visible in the given scope
document.node.getDataType('Customer', 'public');

// Namespaced lookup — resolves from a linked reference document
document.node.getDataType('cm:Customer');

References & namespaces

Use references to link external ApiDocument instances. Types from the linked document are accessible with a namespace:TypeName prefix.

const document = await ApiDocumentFactory.createDocument({
references: {
cm: () => CustomerModelsDocument.create(),
},
api: { ... },
});

// Resolve a type from the linked document
const customerType = document.node.getDataType('cm:Customer');

Each value in references is a thunk — a zero-argument function returning a Promise<ApiDocument> (or a raw init object / URL). Thunks are resolved lazily during createDocument.


API accessors

Use the typed getters or throwing methods to access the transport API:

// Non-throwing — returns undefined if wrong transport
const http = document.httpApi; // HttpApi | undefined
const mq = document.mqApi; // MQApi | undefined
const ws = document.wsApi; // WSApi | undefined

// Throwing — throws TypeError if wrong transport
const http = document.getHttpApi();
const mq = document.getMqApi();
const ws = document.getWsApi();

Exporting the schema

Serialize the document to its JSON schema representation:

// Plain export
const schema = document.export(); // OpraSchema.ApiDocument
const json = JSON.stringify(document); // calls toJSON() internally

// Scoped export — only types and fields visible in 'public' scope
const publicSchema = document.export({ scope: 'public' });
import { writeFileSync } from 'node:fs';
writeFileSync('opra.json', JSON.stringify(document.export(), null, 2));

export() options

OptionTypeDescription
scopestringLimit exported types and fields to those visible in the given scope.