Custom Business Logic with Server Hooks
This guide explains how to implement custom server-side business logic and side effects—such as charging a credit card, dispatching transactional emails, or executing complex multi-step workflows—using Aegil server hooks in hooks/.
Prerequisites
Section titled “Prerequisites”- An existing Aegil project with an entity defined in
specs/<feature>/*.tsp. - Basic familiarity with Serverpod
SessionandTransactionobjects.
Defining a custom mutation in TypeSpec
Section titled “Defining a custom mutation in TypeSpec”When you need business logic beyond standard CRUD operations, declare a custom @mutation in your spec (specs/<feature>/*.tsp):
namespace Helpdesk;
@mutation({ touches: ["Ticket"] })op escalateTicket( ticketId: uuid, assignedAgentId: string): Ticket;When you run aegil build, Aegil scaffolds a starter hook file in hooks/escalate_ticket_hook.dart with a // AEGIL:STUB marker.
Implementing the Hook Handler (hooks/escalate_ticket_hook.dart)
Section titled “Implementing the Hook Handler (hooks/escalate_ticket_hook.dart)”// AGENT-WRITABLE HOOK: Customize side-effects for `escalateTicket` here.import 'package:serverpod/serverpod.dart';import 'package:helpdesk_server/src/generated/protocol.dart';import 'package:helpdesk_server/src/handlers/helpdesk_handlers.g.dart';
class EscalateTicketHook implements EscalateTicketHandler { const EscalateTicketHook();
@override Future<Ticket> execute( Session session, { required Transaction tx, required Ticket target, required String assignedAgentId, }) async { // 1. Perform your custom business logic session.log('Escalating ticket ${target.id} to agent $assignedAgentId');
// 2. Apply required state changes final updated = target.copyWith( status: TicketStatus.escalated, assignedAgentId: assignedAgentId, );
// 3. Save changes within the active transaction return await Ticket.db.updateRow(session, updated, transaction: tx); }}The compiler contract: Preconditions vs. Postconditions
Section titled “The compiler contract: Preconditions vs. Postconditions”When implementing a hook, you do not need to write boilerplate checks. Aegil enforces a strict compiler contract:
Preconditions guaranteed by the compiler
Section titled “Preconditions guaranteed by the compiler”Before your hook’s execute() method is ever called, Aegil has already guaranteed:
- Authentication: The caller has a verified session (their ID and role are valid).
- Transaction: The operation runs inside an active database transaction (
Transaction tx). - Prefetch: The target entity row (
target) has already been fetched from the database. - Policy check: The caller’s CEL
@policypermissions have been verified. - State machine check: The transition from the entity’s current state to the target state has been verified.
Do not re-check preconditions: You do not need to check if the caller is authorized or if the record exists; Aegil has already verified this.
Postconditions required from your hook
Section titled “Postconditions required from your hook”Your hook is only responsible for executing the business side-effect and returning the resulting entity in the expected final state.
Important: Rebuild after editing hooks (ERR_STALE_HOOK_MIRROR)
Section titled “Important: Rebuild after editing hooks (ERR_STALE_HOOK_MIRROR)”Hooks are written in your hand-written hooks/ directory (Zone 2) and mirrored into the Serverpod server during compilation:
# 1. Edit your hook in hooks/# 2. Run build to mirror the hook into the serveraegil build
# 3. Run verificationaegil verifyIf you edit a hook and run aegil verify without building first, Aegil stops with ERR_STALE_HOOK_MIRROR to prevent running tests against outdated code.
What could go wrong?
Section titled “What could go wrong?”| What you see | Why | What to do |
|---|---|---|
ERR_STALE_HOOK_MIRROR |
A hook file in hooks/ was modified, but aegil build was not run. |
Run aegil build to mirror your hook into the server. |
ERR_MISSING_HOOK_IMPLEMENTATION |
A @mutation was declared in specs, but no handler class was registered. |
Implement the generated Handler interface in hooks/ and rebuild. |
Postcondition failure in verify |
The hook did not leave the entity in the state required by the state machine. | Update the hook to assign the expected state before saving. |
Next steps
Section titled “Next steps”- Learn Flutter UI & Reactive BLoCs.
- Learn Spec-Diff Database Migrations.
- Learn The 3-Step Agent Protocol.