Operations: Queries, Mutations & Streams
This guide shows how to declare API operations in TypeSpec—including automated database queries with cursor pagination, auto-mutations with cache invalidation, real-time WebSocket streams, and custom server hooks.
Prerequisites
Section titled “Prerequisites”- An existing Aegil project with at least one model declared in
specs/<feature>/*.tsp. - Basic understanding of TypeSpec syntax and types.
Overview: The declarative API contract
Section titled “Overview: The declarative API contract”In traditional stacks, building a feature requires writing:
- An HTTP route or RPC endpoint on the server.
- A database query or mutation with transaction boundaries.
- Serialization and deserialization boilerplate on both ends.
- A client service, network caller, and state management class (BLoC/Notifier).
In Aegil, you write one operation signature in TypeSpec. The compiler generates the Serverpod endpoint, SQL query, network protocol, and reactive Flutter BLoC automatically.
Auto-Queries (@autoQuery)
Section titled “Auto-Queries (@autoQuery)”The @autoQuery decorator generates an end-to-end read endpoint with built-in database queries, pagination, and Flutter state management.
@public@autoQuery({ entity: "Note", paginate: "cursor", filterBy: ["ownerId"], sortBy: ["createdAt"]})op listNotes(ownerId?: uuid, limit?: int): Page<Note>;Decorator parameters
Section titled “Decorator parameters”| Parameter | Type | Description |
|---|---|---|
entity |
string |
The target model name to query. |
paginate |
"cursor" | "offset" |
The pagination strategy. Cursor-based pagination is recommended for high-performance and infinite scrolling. |
filterBy |
string[] |
Fields that clients can filter by as query parameters. |
sortBy |
string[] |
Allowed database sort columns. |
What @autoQuery generates
Section titled “What @autoQuery generates”- Serverpod Endpoint: Generates
server/lib/src/endpoints/note_endpoint.g.dartexecuting parameterized SQL queries against PostgreSQL. - Cursor Pagination: Returns a
Page<Note>containingitems,nextCursor, andhasMore. - Flutter BLoC: Generates
NoteBlocwithListNotesRequested(limit: ..., filter: ...)inclient/lib/api.dart.
// Flutter UI usagecontext.read<NoteBloc>().add(const ListNotesRequested(limit: 50));Auto-Mutations (@autoMutation)
Section titled “Auto-Mutations (@autoMutation)”The @autoMutation decorator generates create, update, or delete endpoints without hand-written database code.
@public@autoMutation({ entity: "Note", action: "create", touches: ["Note"]})op addNote(title: string, content: string): Note;Decorator parameters
Section titled “Decorator parameters”| Parameter | Type | Description |
|---|---|---|
entity |
string |
The target model name being modified. |
action |
"create" | "update" | "delete" |
The CRUD operation performed. |
touches |
string[] |
Entities whose caches must be invalidated upon successful execution. |
Cache invalidation with touches
Section titled “Cache invalidation with touches”When addNote completes successfully, Aegil automatically invalidates any cached queries observing Note. The Flutter NoteBloc immediately refreshes its items in memory without requiring manual UI re-fetching logic.
Real-Time Streams (@autoStream)
Section titled “Real-Time Streams (@autoStream)”To push database changes to connected clients over WebSockets in real time, use @autoStream:
@autoStream({ entity: "Ticket" })op watchTickets(): Stream<Ticket>;How Real-Time Streams work
Section titled “How Real-Time Streams work”- Serverpod Streaming: Serverpod opens an active WebSocket connection between the client and server.
- Event Emission: Whenever an
@autoMutationmodifyingTicketsucceeds, the server broadcasts the updated entity to listening sessions. - Flutter UI: The generated
TicketBloclistens to the stream and yields new states automatically:
BlocProvider( create: (_) => TicketBloc(client: client, enableRealtimeStream: true), child: const TicketScreen(),)Custom Mutations (@mutation) and Server Hooks
Section titled “Custom Mutations (@mutation) and Server Hooks”For complex business logic—such as processing Stripe payments, issuing third-party API calls, or enforcing multi-entity state transitions—use @mutation.
@mutationop escalateTicket(ticketId: uuid, reason: string): Ticket;Unlike @autoMutation, @mutation does not generate auto-CRUD SQL. Instead, it generates a Server Business Hook contract:
- The compiler generates an abstract handler interface in
.aegil/server/. - The Action Manifest lists a pending task for
hooks/escalate_ticket_hook.dart. - You implement the business logic in Zone 2:
import 'package:helpdesk_server/api.dart';
class EscalateTicketHook implements EscalateTicketHandler { @override Future<Ticket> handle(Session session, EscalateTicketInput input) async { // Auth, transactions, and CEL policy checks are already verified by the compiler! // Write your isolated business side-effects here: final ticket = await Ticket.db.findById(session, input.ticketId); ticket.status = TicketStatus.Escalated; await ticket.save(session); return ticket; }}Authentication and @public
Section titled “Authentication and @public”By default, every operation requires an authenticated user session. The compiler automatically verifies that a valid session token exists before executing endpoint logic.
Making operations public
Section titled “Making operations public”For onboarding, login, public landing pages, or public counters, attach @public:
// Accessible to anyone without signing in@public@autoQuery({ entity: "Article", paginate: "cursor", filterBy: [], sortBy: ["publishedAt"] })op listPublicArticles(): Page<Article>;[!WARNING] Operations targeting entities with
@policyrules cannot be marked@publicif the policy relies onauth.idorauth.role. Doing so triggersERR_PUBLIC_ON_PROTECTED_ENTITYat compile time.
Next steps
Section titled “Next steps”- Read how CEL policies safeguard operations in Access Control & CEL Policies.
- Learn about finite state machines in State Machines & Lifecycle.
- Check the full syntax in Keywords & Decorators Reference.