Skip to content

Tutorial: build a feature ​

One page for every option

This page covers every choice of --Persistence, --Auth, --IncludeTests and --Aspire. A label says which options a part is for; the copy in your app's docs/ folder has only yours. ApiHost stands for your app's name.

This tutorial adds a real feature to ApiHost from start to finish: Contacts, a small address book.

With organisations

Contacts belong to an organisation, so every member sees the same list.

With accounts, without organisations

Each user has their own contacts.

Without accounts

Everyone shares one list of contacts.

By the end, you'll have:

  • Marten the data, stored as JSON documents with Marten;
  • EF Core the data, stored with EF Core, with a migration;
  • HTTP endpoints to add, list and delete contacts, with validation;
  • a message handled in the background, through Wolverine's transactional outbox;
  • live updates, so every open tab shows a new contact at once;
  • a React page with TanStack Query;
  • API tests and a client test.

Each step shows the code to write and explains why it's written that way. The Todo feature uses the same patterns, with more besides; Architecture goes through it.

Before you start ​

Have the app running as the README describes: docker compose up -d, the API (dotnet run --project src/ApiHost) and the client (npm run dev in src/Client). Development generates Wolverine's code at runtime, so the API only needs restarting when you add files, not to pick up every change.

All paths below are from the repository root. The new files go in src/ApiHost/Features/Contacts/ and src/Client/src/features/contacts/: a feature keeps its code together, and nothing needs registering, because Wolverine finds endpoints by their attributes and handlers by their names.

1. The data ​

A contact has a name and, optionally, an email address.

With organisations

It belongs to an organisation. The app never sets or checks the organisation itself: a class that implements ITenanted gets a tenant id, which Wolverine fills in from the request's organisation and adds to every query. One organisation can't see another's contacts, even by mistake.

With accounts, without organisations

It belongs to the user who added it, by their user id. Every query filters on the owner, so one user can't see another's contacts.

csharp
using System.Text.Json.Serialization;
using JasperFx.MultiTenancy;

namespace ApiHost.Features.Contacts;

// ITenanted: each contact belongs to an organisation (the tenant). Wolverine sets TenantId when a
// contact is stored, and only finds the request's organisation's contacts.
public class Contact : ITenanted
{
    public Guid Id { get; set; }

    [JsonIgnore]
    public string? TenantId { get; set; }

    public string Name { get; set; } = string.Empty;
    public string? Email { get; set; }
}
csharp
namespace ApiHost.Features.Contacts;

public class Contact
{
    public Guid Id { get; set; }
    public string OwnerId { get; set; } = string.Empty;
    public string Name { get; set; } = string.Empty;
    public string? Email { get; set; }
}
csharp
namespace ApiHost.Features.Contacts;

public class Contact
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string? Email { get; set; }
}

Marten

Marten stores each contact as a JSON document in its own table, which it creates when the app starts.

With organisations

Tell Marten that contacts belong to organisations, in src/ApiHost/Data/Marten/MartenPersistence.cs. It adds a tenant id column, next to the Todos' line:

csharp
using ApiHost.Features.Contacts;
using ApiHost.Features.Todos;
csharp
        opts.Schema.For<Todo>().MultiTenanted();
        opts.Schema.For<Contact>().MultiTenanted();

With accounts, without organisations

Index the owner, so listing a user's contacts stays fast, in src/ApiHost/Data/Marten/MartenPersistence.cs:

csharp
using ApiHost.Features.Contacts;
using ApiHost.Features.Todos;
csharp
            opts.Schema.For<Todo>()
                .Index(t => t.OwnerId);

            opts.Schema.For<Contact>()
                .Index(c => c.OwnerId);

Without accounts

There's nothing to configure.

EF Core

EF Core needs a table for contacts. Add a DbSet to src/ApiHost/Data/EfCore/AppDbContext.cs:

csharp
using ApiHost.Features.Contacts;
using ApiHost.Features.Todos;
csharp
    public DbSet<Todo> Todos => Set<Todo>();

    public DbSet<Contact> Contacts => Set<Contact>();

With organisations

Wolverine adds a tenant id column to every ITenanted entity and filters on it, so there's nothing else to configure.

With accounts, without organisations

In the same file's OnModelCreating, index the owner, so listing a user's contacts stays fast:

csharp
        modelBuilder.Entity<Todo>()
            .HasIndex(t => t.OwnerId);

        modelBuilder.Entity<Contact>()
            .HasIndex(c => c.OwnerId);

Then create the migration that adds the table. Install the EF Core tools once with dotnet tool install --global dotnet-ef, then:

bash
dotnet ef migrations add AddContacts --project src/ApiHost --output-dir Data/EfCore/Migrations

Read the migration it writes in src/ApiHost/Data/EfCore/Migrations/. The app applies it when it starts, here and in production (more about migrations).

2. The request and its validation ​

POST /api/contacts takes a name and an email address. A FluentValidation validator checks them before the endpoint runs: Wolverine finds it (opts.UseFluentValidation() in Program.cs), and answers an invalid request with 400 Bad Request and a ProblemDetails body that lists the errors, which the client shows.

csharp
using FluentValidation;
using Wolverine.Http;

namespace ApiHost.Features.Contacts;

// The body of POST /api/contacts.
public record AddContact(string Name, string? Email);

public class AddContactValidator : AbstractValidator<AddContact>
{
    public AddContactValidator()
    {
        RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
        RuleFor(x => x.Email).EmailAddress().MaximumLength(256).When(x => !string.IsNullOrEmpty(x.Email));
    }
}

// The response: 201 Created, with the new contact's id, and its URL in the Location header.
public record ContactCreationResponse : CreationResponse
{
    public ContactCreationResponse(Guid id) : base($"/api/contacts/{id}")
    {
        Id = id;
    }

    public Guid Id { get; }
}

3. Messages ​

Two messages tell the rest of the app what happened:

  • ContactAdded is for work that shouldn't hold up the request: here, telling open tabs. It's handled in the background (step 5).
  • ContactsChanged goes to browsers over SignalR, so open tabs refresh their list. The client recognises it by the name in [MessageIdentity], contacts-changed, not by its .NET name.

With organisations

ContactsChanged goes only to the organisation's members: each browser connection joins a group for its organisation (Realtime/RealtimeGroups.cs).

With accounts, without organisations

ContactsChanged goes only to the contact's owner: each browser connection joins a group for its user (Realtime/RealtimeGroups.cs).

csharp
using ApiHost.Realtime;
using Wolverine.Attributes;
using Wolverine.SignalR;

namespace ApiHost.Features.Contacts;

// Published when a contact is added; ContactAddedHandler handles it in the background.
public record ContactAdded(Guid ContactId);

// Pushed to browsers over SignalR when a contact is added or deleted.
[MessageIdentity("contacts-changed")]
public record ContactsChanged(Guid ContactId);

public static class ContactNotifications
{
    // To every open tab of the organisation's members, and nobody else's.
    public static object Changed(Guid contactId, string organisationId)
        => new ContactsChanged(contactId).ToWebSocketGroup(RealtimeGroups.Organisation(organisationId));
}
csharp
using ApiHost.Realtime;
using Wolverine.Attributes;
using Wolverine.SignalR;

namespace ApiHost.Features.Contacts;

// Published when a contact is added; ContactAddedHandler handles it in the background.
public record ContactAdded(Guid ContactId, string OwnerId);

// Pushed to browsers over SignalR when a contact is added or deleted.
[MessageIdentity("contacts-changed")]
public record ContactsChanged(Guid ContactId);

public static class ContactNotifications
{
    // To every open tab of the contact's owner, and nobody else's.
    public static object Changed(Guid contactId, string ownerId)
        => new ContactsChanged(contactId).ToWebSocketGroup(RealtimeGroups.User(ownerId));
}
csharp
using Wolverine.Attributes;

namespace ApiHost.Features.Contacts;

// Published when a contact is added; ContactAddedHandler handles it in the background.
public record ContactAdded(Guid ContactId);

// Pushed to browsers over SignalR when a contact is added or deleted.
[MessageIdentity("contacts-changed")]
public record ContactsChanged(Guid ContactId);

public static class ContactNotifications
{
    // To every connected browser.
    public static object Changed(Guid contactId) => new ContactsChanged(contactId);
}

Route ContactsChanged to SignalR in src/ApiHost/Program.cs, next to the Todos' messages:

csharp
using ApiHost.Errors;
using ApiHost.Features.Contacts;
csharp
    opts.PublishMessage<TodoChanged>().ToSignalR();
    opts.PublishMessage<ContactsChanged>().ToSignalR();

4. The endpoints ​

An endpoint is a static method with a route attribute. Wolverine passes in what its parameters ask for: the request body, services such as the database session, the signed-in user, and route values such as {id}.

What an endpoint returns matters too. The first value is the response; anything after it is a message to send. Wolverine saves the changes and the messages in one database transaction (the transactional outbox): if saving fails, no message is sent, and once it succeeds, the messages are delivered even if the app stops straight afterwards. That's why Add returns ContactAdded rather than doing the follow-up work itself.

With organisations

[Authorize] means only signed-in users can call them; anyone else gets 401 Unauthorized. The organisation comes from the user's access token. The session Wolverine passes in is for that organisation, so List returns only its contacts, and Delete can't find another organisation's contact: it answers 404 Not Found, as for a contact that doesn't exist.

With accounts, without organisations

[Authorize] means only signed-in users can call them; anyone else gets 401 Unauthorized. Delete answers 404 Not Found for someone else's contact, as for one that doesn't exist, so nobody can find out which ids exist.

Marten

csharp
using System.Security.Claims;
using ApiHost.Identity;
using ApiHost.Organisations;
using Marten;
using Microsoft.AspNetCore.Authorization;
using Wolverine;
using Wolverine.Http;

namespace ApiHost.Features.Contacts;

public static class ContactEndpoints
{
    [Authorize]
    [WolverinePost("/api/contacts")]
    public static (ContactCreationResponse, ContactAdded) Add(AddContact request, IDocumentSession session)
    {
        var contact = new Contact { Id = Guid.CreateVersion7(), Name = request.Name, Email = request.Email };

        // Saved when the endpoint returns, in the same transaction as ContactAdded.
        session.Store(contact);
        return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id));
    }

    [Authorize]
    [WolverineGet("/api/contacts")]
    public static Task<IReadOnlyList<Contact>> List(IQuerySession session, CancellationToken cancellationToken)
        => session.Query<Contact>().OrderBy(c => c.Name).ToListAsync(cancellationToken);

    [Authorize]
    [WolverineDelete("/api/contacts/{id}")]
    public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, IDocumentSession session, ClaimsPrincipal user, CancellationToken cancellationToken)
    {
        var contact = await session.LoadAsync<Contact>(id, cancellationToken);
        if (contact is null)
        {
            return (Results.NotFound(), []);
        }

        session.Delete(contact);
        return (Results.NoContent(), [ContactNotifications.Changed(contact.Id, user.GetOrganisationId().ToString())]);
    }
}
csharp
using System.Security.Claims;
using ApiHost.Identity;
using Marten;
using Microsoft.AspNetCore.Authorization;
using Wolverine;
using Wolverine.Http;

namespace ApiHost.Features.Contacts;

public static class ContactEndpoints
{
    [Authorize]
    [WolverinePost("/api/contacts")]
    public static (ContactCreationResponse, ContactAdded) Add(AddContact request, IDocumentSession session, ClaimsPrincipal user)
    {
        var contact = new Contact { Id = Guid.CreateVersion7(), OwnerId = user.GetUserId(), Name = request.Name, Email = request.Email };

        // Saved when the endpoint returns, in the same transaction as ContactAdded.
        session.Store(contact);
        return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id, contact.OwnerId));
    }

    [Authorize]
    [WolverineGet("/api/contacts")]
    public static Task<IReadOnlyList<Contact>> List(IQuerySession session, ClaimsPrincipal user, CancellationToken cancellationToken)
    {
        var ownerId = user.GetUserId();
        return session.Query<Contact>().Where(c => c.OwnerId == ownerId).OrderBy(c => c.Name).ToListAsync(cancellationToken);
    }

    [Authorize]
    [WolverineDelete("/api/contacts/{id}")]
    public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, IDocumentSession session, ClaimsPrincipal user, CancellationToken cancellationToken)
    {
        var contact = await session.LoadAsync<Contact>(id, cancellationToken);
        if (contact is null || contact.OwnerId != user.GetUserId())
        {
            return (Results.NotFound(), []);
        }

        session.Delete(contact);
        return (Results.NoContent(), [ContactNotifications.Changed(contact.Id, contact.OwnerId)]);
    }
}
csharp
using Marten;
using Wolverine;
using Wolverine.Http;

namespace ApiHost.Features.Contacts;

public static class ContactEndpoints
{
    [WolverinePost("/api/contacts")]
    public static (ContactCreationResponse, ContactAdded) Add(AddContact request, IDocumentSession session)
    {
        var contact = new Contact { Id = Guid.CreateVersion7(), Name = request.Name, Email = request.Email };

        // Saved when the endpoint returns, in the same transaction as ContactAdded.
        session.Store(contact);
        return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id));
    }

    [WolverineGet("/api/contacts")]
    public static Task<IReadOnlyList<Contact>> List(IQuerySession session, CancellationToken cancellationToken)
        => session.Query<Contact>().OrderBy(c => c.Name).ToListAsync(cancellationToken);

    [WolverineDelete("/api/contacts/{id}")]
    public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, IDocumentSession session, CancellationToken cancellationToken)
    {
        var contact = await session.LoadAsync<Contact>(id, cancellationToken);
        if (contact is null)
        {
            return (Results.NotFound(), []);
        }

        session.Delete(contact);
        return (Results.NoContent(), [ContactNotifications.Changed(contact.Id)]);
    }
}

EF Core

csharp
using System.Security.Claims;
using ApiHost.Data.EfCore;
using ApiHost.Identity;
using ApiHost.Organisations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Wolverine;
using Wolverine.Http;

namespace ApiHost.Features.Contacts;

public static class ContactEndpoints
{
    [Authorize]
    [WolverinePost("/api/contacts")]
    public static (ContactCreationResponse, ContactAdded) Add(AddContact request, AppDbContext db)
    {
        var contact = new Contact { Id = Guid.CreateVersion7(), Name = request.Name, Email = request.Email };

        // Saved when the endpoint returns, in the same transaction as ContactAdded.
        db.Contacts.Add(contact);
        return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id));
    }

    [Authorize]
    [WolverineGet("/api/contacts")]
    public static async Task<IReadOnlyList<Contact>> List(AppDbContext db, CancellationToken cancellationToken)
        => await db.Contacts.AsNoTracking().OrderBy(c => c.Name).ToListAsync(cancellationToken);

    [Authorize]
    [WolverineDelete("/api/contacts/{id}")]
    public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, AppDbContext db, ClaimsPrincipal user, CancellationToken cancellationToken)
    {
        var contact = await db.Contacts.FirstOrDefaultAsync(c => c.Id == id, cancellationToken);
        if (contact is null)
        {
            return (Results.NotFound(), []);
        }

        db.Contacts.Remove(contact);
        return (Results.NoContent(), [ContactNotifications.Changed(contact.Id, user.GetOrganisationId().ToString())]);
    }
}
csharp
using System.Security.Claims;
using ApiHost.Data.EfCore;
using ApiHost.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Wolverine;
using Wolverine.Http;

namespace ApiHost.Features.Contacts;

public static class ContactEndpoints
{
    [Authorize]
    [WolverinePost("/api/contacts")]
    public static (ContactCreationResponse, ContactAdded) Add(AddContact request, AppDbContext db, ClaimsPrincipal user)
    {
        var contact = new Contact { Id = Guid.CreateVersion7(), OwnerId = user.GetUserId(), Name = request.Name, Email = request.Email };

        // Saved when the endpoint returns, in the same transaction as ContactAdded.
        db.Contacts.Add(contact);
        return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id, contact.OwnerId));
    }

    [Authorize]
    [WolverineGet("/api/contacts")]
    public static async Task<IReadOnlyList<Contact>> List(AppDbContext db, ClaimsPrincipal user, CancellationToken cancellationToken)
    {
        var ownerId = user.GetUserId();
        return await db.Contacts.AsNoTracking().Where(c => c.OwnerId == ownerId).OrderBy(c => c.Name).ToListAsync(cancellationToken);
    }

    [Authorize]
    [WolverineDelete("/api/contacts/{id}")]
    public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, AppDbContext db, ClaimsPrincipal user, CancellationToken cancellationToken)
    {
        var contact = await db.Contacts.FirstOrDefaultAsync(c => c.Id == id, cancellationToken);
        if (contact is null || contact.OwnerId != user.GetUserId())
        {
            return (Results.NotFound(), []);
        }

        db.Contacts.Remove(contact);
        return (Results.NoContent(), [ContactNotifications.Changed(contact.Id, contact.OwnerId)]);
    }
}
csharp
using ApiHost.Data.EfCore;
using Microsoft.EntityFrameworkCore;
using Wolverine;
using Wolverine.Http;

namespace ApiHost.Features.Contacts;

public static class ContactEndpoints
{
    [WolverinePost("/api/contacts")]
    public static (ContactCreationResponse, ContactAdded) Add(AddContact request, AppDbContext db)
    {
        var contact = new Contact { Id = Guid.CreateVersion7(), Name = request.Name, Email = request.Email };

        // Saved when the endpoint returns, in the same transaction as ContactAdded.
        db.Contacts.Add(contact);
        return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id));
    }

    [WolverineGet("/api/contacts")]
    public static async Task<IReadOnlyList<Contact>> List(AppDbContext db, CancellationToken cancellationToken)
        => await db.Contacts.AsNoTracking().OrderBy(c => c.Name).ToListAsync(cancellationToken);

    [WolverineDelete("/api/contacts/{id}")]
    public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, AppDbContext db, CancellationToken cancellationToken)
    {
        var contact = await db.Contacts.FirstOrDefaultAsync(c => c.Id == id, cancellationToken);
        if (contact is null)
        {
            return (Results.NotFound(), []);
        }

        db.Contacts.Remove(contact);
        return (Results.NoContent(), [ContactNotifications.Changed(contact.Id)]);
    }
}

5. Background work ​

ContactAdded is handled by a class whose name ends in Handler, which is how Wolverine finds it. Its Handle method runs after the request has finished, from a durable queue in PostgreSQL: if it fails, Wolverine retries it, and if the app stops first, it runs after the restart.

This handler only tells open tabs, but this is the place for anything slow or unreliable that follows from adding a contact: sending an email, calling another service, or updating a search index. What it returns is sent on as messages, as with the endpoints.

csharp
using JasperFx.MultiTenancy;

namespace ApiHost.Features.Contacts;

public class ContactAddedHandler
{
    // tenantId: the organisation the contact belongs to. Wolverine carries it on every message
    // sent while handling a request.
    public static object Handle(ContactAdded message, TenantId tenantId, ILogger<ContactAddedHandler> logger)
    {
        logger.LogInformation("Contact {ContactId} was added", message.ContactId);
        return ContactNotifications.Changed(message.ContactId, tenantId.Value);
    }
}
csharp
namespace ApiHost.Features.Contacts;

public class ContactAddedHandler
{
    public static object Handle(ContactAdded message, ILogger<ContactAddedHandler> logger)
    {
        logger.LogInformation("Contact {ContactId} was added", message.ContactId);
        return ContactNotifications.Changed(message.ContactId, message.OwnerId);
    }
}
csharp
namespace ApiHost.Features.Contacts;

public class ContactAddedHandler
{
    public static object Handle(ContactAdded message, ILogger<ContactAddedHandler> logger)
    {
        logger.LogInformation("Contact {ContactId} was added", message.ContactId);
        return ContactNotifications.Changed(message.ContactId);
    }
}

With accounts

Deleting the data with its owner ​

With organisations

When an organisation is deleted, its contacts must go too. The app publishes OrganisationDeleted for that organisation, and any feature can handle it:

Without organisations

When someone deletes their account, their contacts must go too. The app publishes AccountDeleted, and any feature can handle it:

Marten

csharp
using ApiHost.Organisations;
using Marten;

namespace ApiHost.Features.Contacts;

// The message is sent for the deleted organisation, so the session only finds its contacts.
public static class DeleteContactsOfDeletedOrganisationHandler
{
    public static async Task Handle(OrganisationDeleted message, IDocumentSession session, CancellationToken cancellationToken)
    {
        var ids = await session.Query<Contact>().Select(c => c.Id).ToListAsync(cancellationToken);
        foreach (var id in ids)
        {
            session.Delete<Contact>(id);
        }
    }
}
csharp
using ApiHost.Identity;
using Marten;

namespace ApiHost.Features.Contacts;

public static class DeleteContactsOfDeletedAccountHandler
{
    public static void Handle(AccountDeleted message, IDocumentSession session)
        => session.DeleteWhere<Contact>(c => c.OwnerId == message.UserId);
}

EF Core

csharp
using ApiHost.Data.EfCore;
using ApiHost.Organisations;
using Microsoft.EntityFrameworkCore;

namespace ApiHost.Features.Contacts;

// The message is sent for the deleted organisation, so the DbContext only sees its contacts; the
// filter on TenantId is a second guard.
public static class DeleteContactsOfDeletedOrganisationHandler
{
    public static async Task Handle(OrganisationDeleted message, AppDbContext db, CancellationToken cancellationToken)
    {
        var organisationId = message.OrganisationId.ToString();
        await db.Contacts.Where(c => c.TenantId == organisationId).ExecuteDeleteAsync(cancellationToken);
    }
}
csharp
using ApiHost.Data.EfCore;
using ApiHost.Identity;
using Microsoft.EntityFrameworkCore;

namespace ApiHost.Features.Contacts;

public static class DeleteContactsOfDeletedAccountHandler
{
    public static async Task Handle(AccountDeleted message, AppDbContext db, CancellationToken cancellationToken)
        => await db.Contacts.Where(c => c.OwnerId == message.UserId).ExecuteDeleteAsync(cancellationToken);
}

6. Try the API ​

Restart the API, since you added files, and open the API reference at http://localhost:5133/scalar/, which lists the new endpoints. You can call them from there, or go straight on to the page.

With accounts

They need an access token: sign in with POST /api/auth/login (demo@example.com, Demo123!) and use the accessToken it returns.

7. The client's API types ​

The client calls the API through a typed client (src/Client/src/lib/api/client.ts), whose types are generated from the API's OpenAPI document. With the API running, update them:

bash
cd src/Client
npm run gen:api

src/Client/src/lib/api/schema.d.ts now has /api/contacts, so TypeScript checks every call's path, parameters and body.

8. Queries ​

TanStack Query fetches and caches the list. The add and delete mutations mark it stale when they succeed, and it's fetched again wherever it's shown.

ts
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../../lib/api/client'
import { problemMessage } from '../../lib/api/problemDetails'

// The contact list's cache key: anything that changes contacts invalidates it.
export const contactKeys = {
  all: ['contacts'] as const,
}

export function useContacts() {
  return useQuery({
    queryKey: contactKeys.all,
    // Contacts also change in other tabs, so fetch them again whenever the page opens.
    refetchOnMount: 'always',
    queryFn: async () => {
      const { data, response } = await api.GET('/api/contacts')
      if (!response.ok || !data) throw new Error('Could not load the contacts.')
      return data
    },
  })
}

export function useAddContact() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async ({ name, email }: { name: string; email: string }) => {
      const { error, response } = await api.POST('/api/contacts', { body: { name, email: email || null } })
      // A validation failure is a 400 with ProblemDetails: show its message.
      if (!response.ok) throw new Error(problemMessage(error, 'Could not add the contact.'))
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey: contactKeys.all }),
  })
}

export function useDeleteContact() {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (id: string) => {
      const { response } = await api.DELETE('/api/contacts/{id}', { params: { path: { id } } })
      if (!response.ok) throw new Error('Could not delete the contact.')
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey: contactKeys.all }),
  })
}

9. The page ​

The page lists the contacts, with a form to add one and a button to delete each. useRealtime listens on the tab's connection to the API's SignalR hub: when contacts-changed arrives, from this tab or another, the list is fetched again. After a reconnect, it's fetched anyway, in case a change was missed.

The components (Button, Input) are shadcn/ui's, in src/Client/src/components/ui/.

tsx
import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useRealtime } from '../../lib/realtime'
import { contactKeys, useAddContact, useContacts, useDeleteContact } from './contactQueries'

export function ContactsPage() {
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const contacts = useContacts()
  const addContact = useAddContact()
  const deleteContact = useDeleteContact()
  const queryClient = useQueryClient()

  // Live updates: a contact was added or deleted, here or in another tab.
  useRealtime(
    (message) => {
      if (message.type === 'contacts-changed') void queryClient.invalidateQueries({ queryKey: contactKeys.all })
    },
    () => void queryClient.invalidateQueries({ queryKey: contactKeys.all }),
  )

  function add(event: React.FormEvent) {
    event.preventDefault()
    if (!name.trim()) return
    addContact.mutate(
      { name, email },
      {
        onSuccess: () => {
          setName('')
          setEmail('')
        },
      },
    )
  }

  return (
    <div className="mx-auto max-w-xl px-6 py-10">
      <h1 className="mb-4 text-2xl font-semibold">Contacts</h1>

      <form onSubmit={add} className="mb-4 flex flex-wrap gap-2">
        <Input className="flex-1" value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" />
        <Input className="flex-1" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email (optional)" />
        <Button type="submit" disabled={addContact.isPending}>
          Add
        </Button>
      </form>

      {(addContact.error ?? deleteContact.error) && (
        <p role="alert" className="mb-4 text-sm text-destructive">
          {(addContact.error ?? deleteContact.error)?.message}
        </p>
      )}

      {contacts.isPending ? (
        <p className="text-muted-foreground">Loading…</p>
      ) : contacts.isError ? (
        <p role="alert" className="text-destructive">
          {contacts.error.message}
        </p>
      ) : contacts.data.length === 0 ? (
        <p className="text-muted-foreground">No contacts yet.</p>
      ) : (
        <ul className="space-y-2">
          {contacts.data.map((contact) => (
            <li key={contact.id} className="flex items-center justify-between gap-3 rounded-lg border bg-card px-3 py-2">
              <span>
                {contact.name}
                {contact.email && <span className="ml-2 text-sm text-muted-foreground">{contact.email}</span>}
              </span>
              <Button
                variant="link"
                type="button"
                className="h-auto px-0"
                aria-label={`Delete ${contact.name}`}
                onClick={() => deleteContact.mutate(contact.id!)}
                disabled={deleteContact.isPending}
              >
                Delete
              </Button>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}

A page also needs a route module, which gives its title:

tsx
import type { PageHandle } from '../components/PageMeta'
import { ContactsPage } from '../features/contacts/ContactsPage'

export const handle: PageHandle = { title: 'Contacts' }

export default ContactsPage

Add its URL to src/Client/src/routes.ts.

With accounts

It goes next to the Todos, inside the require-auth layout, which sends signed-out visitors to the login page and back:

ts
    route('todos', 'routes/todos.tsx'),
    route('contacts', 'routes/contacts.tsx'),

Without accounts

ts
  route('todos', 'routes/todos.tsx'),
  route('contacts', 'routes/contacts.tsx'),

And to src/Client/src/pages.ts, the list of every page that the API and the build read (a unit test checks the two lists match). index: false keeps it out of search engines and the sitemap, as it's for signed-in use:

ts
  { path: '/todos', index: false },
  { path: '/contacts', index: false },

Finally, link to it from the header.

With accounts

The signed-in links are in src/Client/src/features/account/AccountNavigation.tsx:

tsx
      <NavItem to="/todos">Todos</NavItem>
      <NavItem to="/contacts">Contacts</NavItem>

Without accounts

The links are in src/Client/src/App.tsx:

tsx
import { Layout, NavItem } from './components/Layout'

// The frame around every page (root.tsx renders it): the header, the current page and the footer.
export function App() {
  return (
    <Layout
      nav={
        <>
          <NavItem to="/todos">Todos</NavItem>
          <NavItem to="/contacts">Contacts</NavItem>
        </>
      }
    />
  )
}

Open http://localhost:5173/contacts and add a contact. Open the page in a second tab too: a contact added in one appears in the other, through the background handler and SignalR.

10. Tests ​

With the tests

The API ​

The API tests run the whole app in memory against a real PostgreSQL in Docker (Testcontainers), with Alba sending the requests. ExecuteAndWaitAsync also waits for the messages a request sends to be handled, so a test can check that the background work ran.

With accounts

CreateUserAndGetAccessTokenAsync registers a new user each time, so each test has its own data, and the last test checks that one user can't see or delete another's contacts.

csharp
using System.Net;
using Alba;
using ApiHost.Features.Contacts;
using Wolverine.Tracking;

namespace ApiHost.Tests;

[Collection("api")]
public class ContactTests
{
    private readonly AppFixture _fixture;

    public ContactTests(AppFixture fixture)
    {
        _fixture = fixture;
    }

    private async Task<string?> NewUserAsync() => await _fixture.CreateUserAndGetAccessTokenAsync();

    private Task<IScenarioResult> Send(string? token, Action<Scenario> configure) => _fixture.Host.Scenario(s =>
    {
        if (token is not null)
        {
            s.WithBearerToken(token);
        }
        configure(s);
    });

    private async Task<List<Contact>> ListAsync(string? token)
    {
        var result = await Send(token, s =>
        {
            s.Get.Url("/api/contacts");
            s.StatusCodeShouldBeOk();
        });
        return result.ReadAsJson<List<Contact>>()!;
    }

    [Fact]
    public async Task add_list_and_delete_a_contact()
    {
        var token = await NewUserAsync();
        var name = $"Ada Lovelace {Guid.NewGuid()}";

        // Waits for ContactAdded to be handled, too.
        var tracked = await _fixture.Host.ExecuteAndWaitAsync(() => Send(token, s =>
        {
            s.Post.Json(new AddContact(name, "ada@example.com")).ToUrl("/api/contacts");
            s.StatusCodeShouldBe(HttpStatusCode.Created);
        }));

        var contact = Assert.Single(await ListAsync(token), c => c.Name == name);
        Assert.Equal("ada@example.com", contact.Email);
        Assert.Contains(tracked.Executed.MessagesOf<ContactAdded>(), m => m.ContactId == contact.Id);

        await Send(token, s =>
        {
            s.Delete.Url($"/api/contacts/{contact.Id}");
            s.StatusCodeShouldBe(HttpStatusCode.NoContent);
        });
        Assert.DoesNotContain(await ListAsync(token), c => c.Id == contact.Id);

        await Send(token, s =>
        {
            s.Delete.Url($"/api/contacts/{contact.Id}");
            s.StatusCodeShouldBe(HttpStatusCode.NotFound);
        });
    }

    [Theory]
    [InlineData("", null)]
    [InlineData("Ada", "not an email address")]
    public async Task an_invalid_contact_is_rejected(string name, string? email)
    {
        var token = await NewUserAsync();

        await Send(token, s =>
        {
            s.Post.Json(new AddContact(name, email)).ToUrl("/api/contacts");
            s.StatusCodeShouldBe(HttpStatusCode.BadRequest);
        });
    }

    [Fact]
    public async Task nobody_else_can_see_or_delete_a_contact()
    {
        var owner = await NewUserAsync();
        var someoneElse = await NewUserAsync();
        var name = $"Private contact {Guid.NewGuid()}";
        await Send(owner, s =>
        {
            s.Post.Json(new AddContact(name, null)).ToUrl("/api/contacts");
            s.StatusCodeShouldBe(HttpStatusCode.Created);
        });
        var contact = Assert.Single(await ListAsync(owner), c => c.Name == name);

        Assert.DoesNotContain(await ListAsync(someoneElse), c => c.Id == contact.Id);
        await Send(someoneElse, s =>
        {
            s.Delete.Url($"/api/contacts/{contact.Id}");
            s.StatusCodeShouldBe(HttpStatusCode.NotFound);
        });
        await Send(null, s =>
        {
            s.Get.Url("/api/contacts");
            s.StatusCodeShouldBe(HttpStatusCode.Unauthorized);
        });
    }
}
csharp
using System.Net;
using Alba;
using ApiHost.Features.Contacts;
using Wolverine.Tracking;

namespace ApiHost.Tests;

[Collection("api")]
public class ContactTests
{
    private readonly AppFixture _fixture;

    public ContactTests(AppFixture fixture)
    {
        _fixture = fixture;
    }

    // Without accounts, nobody signs in.
    private static Task<string?> NewUserAsync() => Task.FromResult<string?>(null);

    private Task<IScenarioResult> Send(string? token, Action<Scenario> configure) => _fixture.Host.Scenario(s =>
    {
        if (token is not null)
        {
            s.WithBearerToken(token);
        }
        configure(s);
    });

    private async Task<List<Contact>> ListAsync(string? token)
    {
        var result = await Send(token, s =>
        {
            s.Get.Url("/api/contacts");
            s.StatusCodeShouldBeOk();
        });
        return result.ReadAsJson<List<Contact>>()!;
    }

    [Fact]
    public async Task add_list_and_delete_a_contact()
    {
        var token = await NewUserAsync();
        var name = $"Ada Lovelace {Guid.NewGuid()}";

        // Waits for ContactAdded to be handled, too.
        var tracked = await _fixture.Host.ExecuteAndWaitAsync(() => Send(token, s =>
        {
            s.Post.Json(new AddContact(name, "ada@example.com")).ToUrl("/api/contacts");
            s.StatusCodeShouldBe(HttpStatusCode.Created);
        }));

        var contact = Assert.Single(await ListAsync(token), c => c.Name == name);
        Assert.Equal("ada@example.com", contact.Email);
        Assert.Contains(tracked.Executed.MessagesOf<ContactAdded>(), m => m.ContactId == contact.Id);

        await Send(token, s =>
        {
            s.Delete.Url($"/api/contacts/{contact.Id}");
            s.StatusCodeShouldBe(HttpStatusCode.NoContent);
        });
        Assert.DoesNotContain(await ListAsync(token), c => c.Id == contact.Id);

        await Send(token, s =>
        {
            s.Delete.Url($"/api/contacts/{contact.Id}");
            s.StatusCodeShouldBe(HttpStatusCode.NotFound);
        });
    }

    [Theory]
    [InlineData("", null)]
    [InlineData("Ada", "not an email address")]
    public async Task an_invalid_contact_is_rejected(string name, string? email)
    {
        var token = await NewUserAsync();

        await Send(token, s =>
        {
            s.Post.Json(new AddContact(name, email)).ToUrl("/api/contacts");
            s.StatusCodeShouldBe(HttpStatusCode.BadRequest);
        });
    }
}

Run them with dotnet test (Docker must be running).

The page ​

The client's tests render a component with Vitest and React Testing Library, with the API faked by MSW, so they run in a second without the API. The realtime connection is replaced by a stand-in that does nothing.

tsx
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { http, HttpResponse } from 'msw'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { server } from '../../test/server'
import { renderPage } from '../../test/render'
import { ContactsPage } from './ContactsPage'

// No SignalR connection in unit tests.
vi.mock('../../lib/realtime', () => ({ useRealtime: () => {} }))

type Contact = { id: string; name: string; email: string | null }

describe('ContactsPage', () => {
  let contacts: Contact[]

  beforeEach(() => {
    contacts = [{ id: '1', name: 'Ada Lovelace', email: 'ada@example.com' }]
    server.use(
      http.get('*/api/contacts', () => HttpResponse.json(contacts)),
      http.post('*/api/contacts', async ({ request }) => {
        const body = (await request.json()) as { name: string; email: string | null }
        contacts = [...contacts, { id: '2', ...body }]
        return HttpResponse.json({ id: '2' }, { status: 201 })
      }),
      http.delete('*/api/contacts/:id', ({ params }) => {
        contacts = contacts.filter((c) => c.id !== params.id)
        return new HttpResponse(null, { status: 204 })
      }),
    )
  })

  it('adds a contact and shows the refreshed list', async () => {
    renderPage(<ContactsPage />, '/contacts')
    await screen.findByText('Ada Lovelace')

    await userEvent.type(screen.getByPlaceholderText('Name'), 'Grace Hopper')
    await userEvent.click(screen.getByRole('button', { name: 'Add' }))

    expect(await screen.findByText('Grace Hopper')).toBeInTheDocument()
    expect(screen.getByPlaceholderText('Name')).toHaveValue('')
  })

  it('deletes a contact', async () => {
    renderPage(<ContactsPage />, '/contacts')

    await userEvent.click(await screen.findByRole('button', { name: 'Delete Ada Lovelace' }))

    expect(await screen.findByText('No contacts yet.')).toBeInTheDocument()
  })

  it('shows the validation message when adding fails', async () => {
    server.use(
      http.post('*/api/contacts', () =>
        HttpResponse.json({ title: 'Validation failed', errors: { Name: ['Name is too long.'] } }, { status: 400 }),
      ),
    )
    renderPage(<ContactsPage />, '/contacts')
    await screen.findByText('Ada Lovelace')

    await userEvent.type(screen.getByPlaceholderText('Name'), 'Grace Hopper')
    await userEvent.click(screen.getByRole('button', { name: 'Add' }))

    expect(await screen.findByRole('alert')).toHaveTextContent('Name is too long.')
  })
})

Run them with npm test in src/Client. See Testing for the end-to-end tests and more.

What's next ​

The feature works. Some things a real feature often adds:

  • With organisations A plan limit: count contacts against the organisation's plan and answer 402 Payment Required when it's full, as CreateTodoEndpoint does with OpenTodos (Plans, trials and limits).
  • With organisations Webhooks: tell the organisation's webhooks about new contacts with WebhookEvents.Raise, as the Todos do (Integrations).
  • With organisations The data export: include contacts in an organisation's data download, like Features/Todos/TodosOrganisationData.cs.
  • With accounts, without organisations The data export: include contacts in a user's data download, like Features/Todos/TodosPersonalData.cs.
  • Marten Event sourcing: the Todos keep every change as an event, with Marten's event store. Use it when the history matters, such as for an audit trail or undo.
  • EF Core Event sourcing: for a history of every change, see how the Todos are built with Marten in the online documentation.
  • Editing a contact: a PUT /api/contacts/{id} endpoint, with its own validator.

The checklist for adding a feature sums up these steps for next time, and Where to add things lists the places an app plugs into, so your code survives updates from the template.

Documentation for v0.9.0. Released under the MIT licence.