SDK types in your models
Use an SDK type such as TMoney as a field of your own model, add your methods and rules, and send the API part with the generated client.
import { model, type IModel, type ModelInit } from '@exprtlabs/golem/model';
import { asGenObservable } from '@exprtlabs/golem-openapi-ts/mobx';
import { getValidator } from '@exprtlabs/golem/validation';
import { action, computed } from 'mobx';
import type { TMoney } from '../sdk/index.js';
export type TPaymentEditor = IModel<{ money: TMoney; note: string }>;public get summary(): string {
return `${this.money.amount} ${this.money.currency}${this.note ? `: ${this.note}` : ''}`;
}
public setAmount(amount: string): void {
this.money.amount = amount; // The nested money model is observable too.
}
public setCurrency(currency: string): void {
this.money.currency = currency.toUpperCase();
}
public setNote(note: string): void {
this.note = note;
}What an SDK type is
- An SDK holds types, not classes, in both SDK modes. The schema
TMoneygives the typeTMoney(Generated SDK names). - The client returns plain objects of that type. Its dates are already
DateorTemporalvalues (Call operations). - A class with methods, MobX or
instanceofis your own model. You declare it withIModel<…>over the SDK type. - Your
PaymentEditoradds methods and a validation rule fornote. Itsmoneyfield is a plainTMoneyobject.
| Golem mode | Standalone mode | |
|---|---|---|
| Your model reads | The schema graph of the SDK, as data | The TypeScript fields of the SDK type |
| Checks and conversions | One set for the SDK and your models, written by the models job | The SDK keeps its own. Your model gets its own |
| Limits of the schema | Kept in your model, such as maxLength | Only what the TypeScript type states |
| Needs | mode: golem and a model block | A TypeScript type that golem can derive |
Install
npm install @exprtlabs/golem
npm install --save-dev @exprtlabs/golem-model @exprtlabs/golem-openapi-ts typescript@~7.1.0-betaChoose how to build in Build tools. Include both src/**/*.ts and the generated sdk/**/*.ts in your TypeScript program.
Configure both generators
One configuration runs the SDK job first. The model job then resolves SDK types such as TMoney. This example uses golem mode, so the models job writes the checks and conversions of the SDK together with your model.
version: 1
validation: true
openapi-ts:
sdks:
- input: ../server/api/openapi.yaml
output: sdk
name: Payments
mode: golem
extensions:
mobx: {}
model: {}The createPayment operation of the Payments API takes money as a TMoney, not the whole editor. The OpenAPI input is the document that the server's docs job writes. Run golem generate in server/ before you generate the web project. The controller that produces this operation is:
@Post()
@ApiOperation({ operationId: 'createPayment' })
@ApiBadRequestResponse({ description: 'Invalid payment input.' })
@ApiBadGatewayResponse({ description: 'The payment provider declined or is unavailable.' })
async create(@Body() input: TPaymentInput): Promise<TPayment> {
const id = String(nextPaymentId++);
const charge = await this.provider.charge(input.money, `payment-${id}`);
const payment = { id, ...input, charge };
payments.set(payment.id, payment);
return payment;
}mode: golemneeds amodelblock in the same file.- Leave
modeout for a standalone SDK. The model job then derives your model from the TypeScript fields of the SDK type. - With
dates: temporal, the SDK types name the globalTemporal. Add"esnext.temporal"tocompilerOptions.lib, or setskipLibCheck: true, and load aTemporalat run time (Dates and times).
Declare the model
Write the declaration and the PaymentEditor class (extending model<TPaymentEditor>()) at the top of this page with zero imports from generated model files. The SDK import is type-only, so it can point at the sdk/ directory that the SDK job is about to create.
Run npx golem generate. It writes sdk/ and the generated model files inside .golem/models/, leaving src/ clean. Regeneration leaves your PaymentEditor class untouched.
Load and edit
export function examplePayment(): PaymentEditor {
const editor = new PaymentEditor();
editor.setAmount('12.50');
editor.setNote('Order 123');
return editor;
}fromWireFormat loads JSON that did not come through the client into the editor:
export function loadPaymentEditor(wire: unknown): PaymentEditor {
return fromWireFormat<PaymentEditor>(wire); // Builds the editor; its money field is the plain TMoney object.
}- Call
fromWireFormat<T>for your own models only, for data that bypasses the client: a queue message, saved state or test data. - Data from the client needs no conversion call. The client returns checked values, so pass them to the constructor.
Put client data in a model
A model can have the SDK type itself as its fields. IModel<Charge> makes a model with the fields of Charge. The class has its own constructor, and its values come first:
export type TChargeView = IModel<Charge>; // A model over the type itself: its fields are the fields of Charge.
export class ChargeView extends model<TChargeView>() {
public readonly fetchedAt: Temporal.Instant; // App state: not a field of Charge, so it is never sent or checked.
public constructor(values: Partial<ModelInit<TChargeView>>, fetchedAt = Temporal.Now.instant()) {
super(values); // Assigns the fields of Charge first.
this.fetchedAt = fetchedAt;
}
}new ChargeView(response.body)takes the converted body of the client. It runs no second check.super(values)assigns the fields ofChargefirst.fetchedAtis app state. It is not a field ofCharge, so golem never sends or checks it.fromWireFormat<ChargeView>(json)passes values only, sofetchedAttakes its default.- An instance of your model is a valid request body. The client writes its declared fields only.
A model can also hold the type as a field. This model adds isOverdue():
export type TChargeRecord = IModel<{ charge: Charge }>;export class ChargeRecord extends model<TChargeRecord>() {
public isOverdue(today: Temporal.PlainDate): boolean {
return Temporal.PlainDate.compare(this.charge.settlesOn, today) < 0; // The settlement day itself is not overdue.
}
}- The field
charge: Chargeis a plainCharge. ItssettlesOnis aTemporal.PlainDate. isOverduetakes today's date as an argument, so a test can fix the date. The settlement day itself is not overdue.
Levels and limits
- A model over an SDK type has its own level. It may lower the level of the project, and it cannot raise it (validation levels).
- In golem mode, the model keeps the limits of the SDK type, such as
maxLengthandpattern. - The client does not return your model. It returns the SDK type. Build your model where you need it.
Validate and send
Before you send, getValidator(editor).validate({ failFast: false }) checks every field and keeps the errors on the editor for a form (Validate models).
const valid = await getValidator(this.editor).validate({ failFast: false });
if (!valid) {
runInAction(() => { this.saveState = 'idle'; });
return false;
}toWireFormat<TPaymentEditor>(editor, { validate: false }) returns the plain object. The editor passed the check above, so validate: false skips a second one. Its money field is the plain TMoney object that the client sends.
const wire = toWireFormat<TPaymentEditor>(this.editor, { validate: false });
const response = await this.createPayment.execute(
{ body: { merchant, billing, money: this.editor.money, note: wire.note } },
{ signal: controller.signal },
);Full example: examples/payments.
