Skip to content

Define models ​

Declare fields as a type, extend model<T>(), and add behavior in your own class.

ts
import { model, type IModel } from '@exprtlabs/golem/model';
import type { Integer, Maximum, MinLength, Minimum, TSerde } from '@exprtlabs/golem/tags';
import type { fromPriorityWord, toPriorityWord } from './priority-word.js';

export type TTask = IModel<{
  title: string & MinLength<1>;
  done: boolean;
  // Your code sorts by a number from 1 to 3; the JSON carries a word.
  priority: number & Integer & Minimum<1> & Maximum<3> & TSerde<typeof toPriorityWord, typeof fromPriorityWord>;
}>;

export class Task extends model<TTask>() {
  public toggle(): void {
    this.done = !this.done;
  }
}
ts
const PRIORITY_WORDS = ['low', 'normal', 'high'] as const;
export type PriorityWord = (typeof PRIORITY_WORDS)[number];

export function toPriorityWord(value: number): PriorityWord {
  const word = PRIORITY_WORDS[value - 1];
  if (!word) throw new RangeError('Priority must be 1, 2 or 3.');
  return word;
}

export function fromPriorityWord(word: PriorityWord): number {
  return PRIORITY_WORDS.indexOf(word) + 1;
}

priority is a number in your class and a word in JSON. TSerde converts between them.

IObject or IModel ​

Both declare fields. IObject stops there: values stay plain objects, and you call the generated validation and conversion through standalone functions. IModel is an IObject paired with model<T>() from @exprtlabs/golem/model so your class (Task) extends model<TTask>() with zero imports from generated files.

ts
import { model, type IModel, type IObject } from '@exprtlabs/golem/model';

export type TComment = IObject<{ text: string }>;
export type TThread = IModel<{ comments: TComment[] }>;
export class Thread extends model<TThread>() {}

TComment is an IObject: parse<TComment> returns a plain object. TThread is an IModel that nests it: parse<Thread> or Thread.parse builds a Thread whose comments array holds those plain objects.

IObjectIModel
Generatesvalidation and JSON conversion in .golem/models/the same, bound to classes extending model<T>()
Value from parseplain object: parse<TComment>(json)your class with Task.parse(json) or parse<Task>(json); a plain object with parse<TTask>(json)
Methods and gettersnoyes, on your class, plus static parse, fromWireFormat, stringify, toWireFormat, validate and assert
MobXobservable only as a field of a model classobservable fields once your constructor calls asGenObservable(this)
Use it forDTOs and nested datadomain objects with behavior

Declare fields ​

Put declarations in src/**/*.model.ts or src/**/*.models.ts. Set model.suffixes to use other endings, such as .entity.ts, and model.sources to name files directly. A field can have any of the supported shapes and carry validation tags.

A file that imports @exprtlabs/golem must lie where that package resolves, as in a build with tsc: in a folder at or below the one whose node_modules holds it. This holds for each model file and for model.output, where golem writes models.validators.generated.ts. Generation type-checks both and stops with a "Cannot find module" error when the import fails.

Set the validation level of a model ​

The second type argument of IObject and IModel takes { validation: true | false | 'sanity' }. It sets the level of the checks that a call uses when it names none.

OptionDefault level of the model's calls
trueEvery rule
'sanity'The shape only (what sanity checks)
falseNo checks. Golem writes no validators for the model, so a call cannot check it.
  • Without the option, the model uses the project level.
  • The model level is at or below the project level. A higher level stops generation with RUNM1089.
  • A call can choose another level up to the project level (Choose a level for one call).

Model classes and static methods ​

Your class links to its IModel declaration through extends model<TTask>() from @exprtlabs/golem/model, so it can have any name: class PurchaseOrder extends model<TOrder>(). No generated base class is emitted and you write zero imports from generated files. A clean clone type-checks directly before generation runs.

Every class extending model<T>() exposes static convenience methods:

MethodWhat it does
Task.parse(text, options?)Parses JSON text into a Task instance
Task.fromWireFormat(wire, options?)Converts a plain wire object into a Task instance
Task.stringify(value, options?)Validates and serializes a Task to JSON text
Task.toWireFormat(value, options?)Validates and converts a Task to its wire object (WireFormat<TTask>)
Task.validate(value, options?)Checks a value and narrows it to Task
Task.assert(value, options?)Checks a value and returns it typed as Task

Standalone generic calls (parse<Task>(), stringify<Task>(), fromWireFormat<Task>(), toWireFormat<Task>(), validate<Task>(), assertValue<Task>()) continue to work alongside the static methods. For IModel types, use WireFormat<TTask> from @exprtlabs/golem/serde and ModelInit<TTask> from @exprtlabs/golem/model instead of generated type aliases.

A file can export several classes that extend model<T>() directly. Each links to the model, and AdminPayment.parse or parse<AdminPayment> builds an AdminPayment. With one class, the model uses it as its default class. A class that extends another linked class does not link.

All generated model files (local models, controller DTOs, shared models, golem-mode SDK codecs and models.validators.generated.ts) are written inside model.output (default .golem/models/). Zero *.generated.ts files are written beside source files in src/. Do not edit generated files; generation replaces them.

Add behavior ​

Your class holds methods, getters, defaults and extra constructor state. The model<T>() base constructor assigns the supplied values, so call super(values) before you read a field. With MobX, call asGenObservable(this) right after super(values).

toWireFormat emits declared fields only. Getters and other state on your class stay on the instance. A key on an instance that its model does not declare is program state, and codecs ignore it. The exact option of the model decides whether extra keys in input fail validation (options exact and allowAny).

Type-only model files ​

A file that exports only types, such as export type TLabel = IObject<{ text: string }>, needs no import of its generated file. The build tool loads the generated file of each model that one of these names:

  • a parse, stringify, validate, toWireFormat or fromWireFormat call
  • a Nest @Body() or @Query() parameter
  • a Nest handler return

A codec that is still missing at run time throws an error that starts with golem fault. Run golem generate, then build again.

Field names you cannot use ​

A declared field cannot use a name from Object.prototype, such as __proto__, constructor, toString or hasOwnProperty. Generation reports the field. Rename it in the declaration or the OpenAPI schema.

Regenerate ​

After you change a declaration, generate again:

sh
npx golem generate

Generation type-checks the project first, then writes the files:

  • It stops on a TypeScript error in a model source or in a file the job writes. It reports the error in the compiler's form, file(line,column): error TSnnnn: message.
  • A type error in any other file does not stop generation.
  • It replaces all generated files inside model.output (default .golem/models/).
  • Your source files and classes in src/ do not change.

golem build generates first, so a build needs no separate golem generate. In CI, run golem build, or run golem generate and then npx golem check (Generate and watch). You choose whether to ignore or commit the generated files.

Full example: examples/models.