Skip to content

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.

ts
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 }>;
ts
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 TMoney gives the type TMoney (Generated SDK names).
  • The client returns plain objects of that type. Its dates are already Date or Temporal values (Call operations).
  • A class with methods, MobX or instanceof is your own model. You declare it with IModel<…> over the SDK type.
  • Your PaymentEditor adds methods and a validation rule for note. Its money field is a plain TMoney object.
Golem modeStandalone mode
Your model readsThe schema graph of the SDK, as dataThe TypeScript fields of the SDK type
Checks and conversionsOne set for the SDK and your models, written by the models jobThe SDK keeps its own. Your model gets its own
Limits of the schemaKept in your model, such as maxLengthOnly what the TypeScript type states
Needsmode: golem and a model blockA TypeScript type that golem can derive

Install ​

sh
npm install @exprtlabs/golem
npm install --save-dev @exprtlabs/golem-model @exprtlabs/golem-openapi-ts typescript@~7.1.0-beta

Choose 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.

yaml
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:

ts
@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: golem needs a model block in the same file.
  • Leave mode out 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 global Temporal. Add "esnext.temporal" to compilerOptions.lib, or set skipLibCheck: true, and load a Temporal at 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 ​

ts
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:

ts
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:

ts
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 of Charge first. fetchedAt is app state. It is not a field of Charge, so golem never sends or checks it.
  • fromWireFormat<ChargeView>(json) passes values only, so fetchedAt takes 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():

ts
export type TChargeRecord = IModel<{ charge: Charge }>;
ts
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: Charge is a plain Charge. Its settlesOn is a Temporal.PlainDate.
  • isOverdue takes 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 maxLength and pattern.
  • 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).

ts
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.

ts
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.