Skip to content

Write a hook in TypeScript with types

A hook module is TypeScript. The binary removes the types when it loads the module, so a type never changes how a hook runs. Types help you before that: your editor and tsc can tell you that a column does not exist, that a value can be empty, or that a before hook calls ctx.mail.

This guide shows how to get those types, how to write a typed hook, and how to run the check. It assumes that you read Add business logic with hooks.

The type check is optional. If you skip it, nothing else changes. The engine never runs tsc, and a type error never stops a hook from running. The check needs node and the typescript package on your computer.

Run matterdata sdk with the application directory. Add -init the first time:

Terminal window
matterdata sdk my-club -init
wrote my-club/.matterdata/sdk.d.ts (5 tables)
wrote my-club/tsconfig.json
no tsc found: install it in the app with `npm install --save-dev typescript` (in my-club), then `matterdata validate my-club` checks the hooks' types

The command writes two files:

File Content
.matterdata/sdk.d.ts The declaration of @matterdata/sdk: defineHook, the type of ctx, and one row type for each table of the application.
tsconfig.json A minimal project file. The command writes it only with -init, and only when the application has none. It never overwrites a file.

The application must compile. The command stops and prints the errors when it does not.

Run the command again after you change a table. The file is rewritten only when its content changes. validate, dev and deploy also bring an existing file up to date before they run the type check, and they never create it. The content depends only on the model, so two runs give the same bytes. Commit the file if your CI runs tsc without the matterdata binary. Otherwise add .matterdata/ to .gitignore.

The directory starts with a dot, so the engine does not take the file for a hook module. The loaders of install, dev, deploy and test skip every .d.ts file, every directory that starts with a dot, and node_modules.

To write the file somewhere else, pass -out <dir>. When that directory is inside the application, -init puts it in the include of tsconfig.json.

-init writes this file:

{
"compilerOptions": {
"target": "ES2018",
"lib": ["ES2018"],
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"noEmit": true,
"isolatedModules": true,
"moduleDetection": "force",
"types": []
},
"include": ["logic/**/*.ts", ".matterdata/*.d.ts"]
}

target and lib are ES2018, because a hook may use the s flag of a regular expression (see Budgets) and tsc refuses it for an earlier target. lib has no DOM types and types is empty. The sandbox has no fetch, no console and no setTimeout, so tsc refuses a hook that uses them. isolatedModules makes tsc refuse constructs that the binary cannot translate one file at a time.

Terminal window
cd my-club
npm install --save-dev typescript

The commands look for tsc in node_modules/.bin/tsc of the application first, then in PATH. The loaders skip node_modules, so it is never copied by deploy.

Import the row type, and give it to defineHook:

import { defineHook, type EventSignupsRow } from "@matterdata/sdk";
export default defineHook<EventSignupsRow>(async (ctx, row) => {
if (!ctx.user) return;
const event = ctx.db.get("events", row.event_id);
if (!event) return;
await ctx.mail.send({
to: ctx.user.email,
template: "signup-confirmed",
data: { title: event.title, starts_at: event.starts_at },
});
});

row.event_id is a number, ctx.db.get("events", …) returns an EventsRow or null, and event.title is a string. A table name that does not exist, a column that does not exist, and an event that can be missing are errors.

The row type of a table is its name in PascalCase with Row after it: event_signups is EventSignupsRow. A hook sees database column names, so a ref column event is event_id.

The hook runs Type of row Type of before
before insert <Table>Draft not passed
before update, before delete, and before of a transition <Table>Row not passed
after … on a table, after save on a form <Table>Row <Table>Row, or absent when there is no previous row
after of a transition <Table>Row, the row after the move <Table>Row, the row before the move

A before insert hook runs before the row exists. The key id is absent, and the columns that the engine fills (a slug, an unguessable, the audit stamps) are still empty. The Draft type allows that.

The binding of a script to a point is in the .mtd source, so the declaration cannot know it. You state the row type, and tsc checks the rest.

defineHook takes the context type as a second parameter. The default is AfterContext, which has ctx.mail. The engine grants ctx.mail to after hooks only. In a before hook, use BeforeContext so that tsc refuses ctx.mail:

import { defineHook, type BeforeContext, type PostsDraft } from "@matterdata/sdk";
export default defineHook<PostsDraft, BeforeContext>(async (ctx, row) => {
const text = row.body ?? "";
row.words = text.split(/\s+/).filter((w) => w.length > 0).length;
});

Both context types list what the engine grants and nothing else. ctx.http and the write half of ctx.db (insert, update, delete) are not there, because no hook holds them. The declaration is generated from the same table that the sandbox uses, and tests compare the two.

A hook without the generic parameters gets a row whose columns have the type any. It type checks, and it tells you nothing about the columns.

matterdata validate runs tsc --noEmit after it compiles the application and its hook modules. It runs the check only when the application has a tsconfig.json, a tsc is found, and the declaration exists:

Terminal window
matterdata validate my-club
my-club/logic/signup-confirmed.ts:5:34: error TS2345: Argument of type 'number | null' is not assignable to parameter of type 'number'.
matterdata: 1 type error in the hooks of my-club

A type error makes validate exit with status 1. When the check does not run, validate prints one line and goes on:

Line Meaning
type check skipped: no tsconfig.json The application has not opted in.
type check skipped: tsc not found Install typescript in the application, or put tsc in PATH.
type check skipped: no .matterdata/sdk.d.ts: … Without the declaration, every hook fails to find @matterdata/sdk. The line ends with the command that writes it.

Add -typecheck to make a check that did not run an error. Use it in a CI job that must have the check.

matterdata deploy runs the same check on your computer, before it writes any request for the server. A type error stops the deploy. -typecheck works the same way:

Terminal window
matterdata deploy -tenant verein -app my-club -typecheck

matterdata dev runs the check in the background after each save. It does not wait for it. The change is deployed first. The errors appear afterwards as warnings, and they never block a deploy:

dev: deployed expenses: no schema change; window 3 ms; digest 47afc2f085068aff
dev: type check: 1 type error (warnings: nothing is blocked, and expenses serves the saved change)
my-club/logic/signup-confirmed.ts:5:34: error TS2345: …

A check that takes longer than 30 seconds is stopped. tsc is killed with every process that it started.

The server never runs tsc, and it never reads the declaration. A type error has no effect on a tenant, because the type check is a step on your computer.

Column Type in a row Why
int, ref, the id number Values reach the sandbox as JSON, so a number is a double. It is exact up to 2^53 − 1.
money number Whole cents: 12.50 is 1250.
decimal(n) number The value times 10ⁿ: 14.5 is 145 at decimal(1).
bool 0 | 1 SQLite stores a bool as 0 or 1, and the hook reads what is stored.
date IsoDate Text, YYYY-MM-DD.
datetime UtcDateTime Text in UTC, YYYY-MM-DDTHH:MM:SSZ.
enum, the lifecycle state a union of the member names "active" | "passive".
text, long text, markdown, email, slug, unguessable string
a column that can be empty the type | null
a column the engine owns readonly A hook cannot write it: the write is refused.

A field that has no column is not in the row: count, sum, min, max, a computed value, list, one and multi. The img and file fields are in the row as their engine-owned columns (photo, photo_filename, photo_mime, …), all readonly.

A hook sees every column of a row, a sensitive column too. It runs with the authority of the application and not of the reader. See Add business logic with hooks.

ctx.db.get, ctx.db.query and ctx.db.count take a table name and give back the row type of that table. Their filters take the columns of that table. The calls are synchronous, and await is allowed and not needed.

ctx.user is null or an object with id, email, and the row id of each profile of the application (member_id, for a profile named member). ctx.roles is a list of the role names that the application declares, plus public and authenticated. ctx.hook is a string. ctx.error(name, args) takes the name of a message of the app block. The compiler checks that name and its values, and the types do not repeat that check.

tsc checks these things:

  • column names and their types in row, before, and the rows that ctx.db returns;
  • the table names and the filters of ctx.db;
  • the calls that a hook may make in its context: ctx.mail in a before hook, ctx.http, and ctx.db.insert are errors;
  • the values that a hook writes: an enum column takes a member name, and a readonly column is an error;
  • globals that the sandbox does not have, such as fetch and console.

These things are not checked:

  • which row type belongs to which hook point. You write it, as step 3 shows;
  • whether a ctx.error name is declared. matterdata validate checks it, with or without types;
  • whether a mail template exists, and the values of its data;
  • anything at run time. A bool that a hook writes as true is converted and stored, but the type says 0 | 1. A value from outside the model, such as a JSON.parse result, has the type that you give it.

The types do not make a hook safe. The sandbox contains a hook, and tsc does not. A hook that fails the type check still loads and runs.

Website privacy policy