Skip to content
Functioncorev0.14.0

defineGate

Builds a Gate from a check. The check refuses by throwing a Notice or a Silence and passes by returning. Annotate ctx as narrowly as the fields that the check reads because the required context is inferred from it. No annotation defaults to GateContextBase, an agnostic gate that fits every handler.

See also:defineEffectGate, the @Gated decorator from your transport package

defineGate<Name, Ctx>(
    name: Name,
    fn: (ctx: Ctx) => Promisable<void>
): Gate<Ctx, Name>
// a gate factory that takes its own option and closes over it
function MinRoles(min: number): Gate<GateContextBase, 'MinRoles'> {
    return defineGate('MinRoles', (ctx) => {
        if (ctx.memberRoleIds.length < min) throw new NotEnoughRoles(min);
    });
}
// agnostic gate (no ctx annotation): fits any handler
const Owner = defineGate('owner', (ctx) => {
    if (!ctx.userId) throw new NotOwner();
});

Name

The gate's name, captured as a literal for mismatch errors.

Name

The gate's name, captured as a literal for mismatch errors.

Ctx

The context that the check reads, inferred from the ctx annotation.

Ctx

The context that the check reads, inferred from the ctx annotation.

name

name: Name

The gate's name, used in mismatch errors.

fn

fn: (ctx: Ctx) => Promisable<void>

The check, which refuses by throwing a Notice or a Silence and passes by returning.