Skip to content

beforeInsertHook

beforeInsertHook<Brand>(fieldName, codec): (entity) => void

Defined in: src/adapters/typeorm.ts:107

Returns a function suitable for use inside a TypeORM @BeforeInsert() lifecycle hook that auto-generates an Id<Brand> for fieldName when the field is absent (null or undefined) on the entity at insert time. If the field already has a value it is left unchanged.

Requires a codec variant that exposes a synchronous generate() — see IdGeneratingCodec. Only the Timestamp codec and Reverse Timestamp codec qualify; passing an async-generate codec (Opaque, Signed, Wrapped, Digest) is a compile-time type error.

Pair with idTransformer on the same column: idTransformer handles the read/write path; beforeInsertHook handles generation.

Brand extends string

string

IdGeneratingCodec<Brand>

(entity) => void

import { idTransformer, beforeInsertHook } from "@smonn/ids/typeorm";
import { createTimestampId } from "@smonn/ids";
import type { Id } from "@smonn/ids";
import { BeforeInsert, Column, Entity } from "typeorm";
const usr = createTimestampId("usr");
const fillUserId = beforeInsertHook("id", usr);
@Entity()
class User {
@Column({ type: "text", transformer: idTransformer(usr) })
id!: Id<"usr">;
@BeforeInsert()
generateId() {
fillUserId(this);
}
}

Gating rule: beforeInsertHook requires a synchronous generate() codec (IdGeneratingCodec). Async-generate codecs — Opaque Timestamp, Signed Timestamp, Wrapped key, and Digest — do not satisfy IdGeneratingCodec and cannot be passed here. TypeORM @BeforeInsert can be async, but synchronous generation keeps the hook ergonomic and matches the full Prisma parity shape.

Read/write path: Use idTransformer on the column for database read/write transforms. beforeInsertHook only handles the generation step — it does not replace the transformer.