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' },
  }),
) // true

Policy.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.define creates a typed table definition; NoteFields.fields exposes typed references to its columns.
  • Guards.declare registers a named guard set ('Notes'). key extracts a stable user ID for cache scoping, and unguarded: 'deny' closes any action you omit (use 'allow' for open-by-default).
  • guard.principal() declares a server-only check by name. Its function lives in G.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 time user.id is an input placeholder (not a real user), so both SQL compilers and in-memory evaluators can inspect Expr.eq(...).
  • Policy is the executable server half. G.implement requires a body for every principal guard (receiving Option<User>, none for visitors) and rejects missing or extra keys in TypeScript.
  • Policy.decide tests one guard against a principal, an action name ('Read', 'Create', 'Update', 'Delete', or a custom name), and an optional row.