Guard / How Guard works
Write your first guard set
This example defines a Note table, declares an admin check and an author check, and evaluates whether a member can read their own note:
ts
import { Effect, Option, Schema } from 'effect'
import { Entity, Expr } from 'foldkit-entity'
import { Guards } from 'foldkit-guard'
const User = Schema.Struct({ id: Schema.String, role: Schema.Literals(['admin', 'member']) })
const NoteFields = Entity.define(
'Note',
Schema.Struct({ id: Schema.String, authorId: Schema.String, title: Schema.String }),
)
const G = Guards.declare(
'Notes',
User,
guard => ({
isAdmin: guard.principal(),
isAuthor: guard.row(NoteFields, user => Expr.eq(NoteFields.fields.authorId, user.id)),
}),
{ key: user => user.id, unguarded: 'deny' },
)
const Policy = G.implement({
isAdmin: principal => Option.exists(principal, user => user.role === 'admin'),
})
Effect.runSync(
Policy.decide(G.isAuthor, {
principal: Option.some({ id: 'ada', role: 'member' }),
interaction: 'Read',
row: { id: 'n1', authorId: 'ada', title: 'Draft' },
}),
) // truePolicy.decide returns an Effect that resolves to true for Ada's note and false if authorId is someone else. Passing Option.none() for a signed-out visitor also returns false.
Here is what each part does:
Entity.definecreates a typed table definition;NoteFields.fieldsexposes typed references to its columns.Guards.declareregisters a named guard set ('Notes').keyextracts a stable user ID for cache scoping, andunguarded: 'deny'closes any action you omit (use'allow'for open-by-default).guard.principal()declares a server-only check by name. Its function lives inG.implement, so your role logic stays out of browser bundles.guard.row(NoteFields, user => ...)builds a frozen expression tree (Expr) instead of a runtime callback. At declaration timeuser.idis an input placeholder (not a real user), so both SQL compilers and in-memory evaluators can inspectExpr.eq(...).Policyis the executable server half.G.implementrequires a body for every principal guard (receivingOption<User>, none for visitors) and rejects missing or extra keys in TypeScript.Policy.decidetests one guard against a principal, an action name ('Read','Create','Update','Delete', or a custom name), and an optional row.