Skip to content

Add a feature ​

What 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 the parts for yours. ApiHost stands for your app's name.

How to add a feature of your own, such as invoices, projects or bookings, from its data to its page and its tests. Each step says what to add, where, and why. The tutorial builds a complete example, Contacts, with all the code; the steps below name the tutorial's step that shows each one. The Todos are a larger example (Architecture).

The examples use a feature called Projects: replace it with yours. Work through the sections in order.

Before you start ​

Have the app running (README): updating the client's API types needs the API. Commit what you have, so you can see the feature's changes on their own.

Add the data ​

Create a folder for the feature, src/ApiHost/Features/Projects/. Everything the feature needs on the server goes there. Nothing needs registering: Wolverine finds endpoints by their attributes and handlers by their class names.

With organisations

Add a class for the data, with a Guid Id. Implement ITenanted, so each project belongs to the organisation of the request that created it, and every query sees only that organisation's projects. There's no filter to remember in each endpoint.

With accounts, without organisations

Add a class for the data, with a Guid Id and an OwnerId, the id of the user it belongs to. Every query and change you write must check the owner, so people only ever see their own data.

Without accounts

Add a class for the data, with a Guid Id. Everyone using the app shares it.

Tutorial: step 1, The data.

Store it ​

Marten, with organisations

Marten creates the table when the app starts, so there's no migration. Tell it the data belongs to organisations, in src/ApiHost/Data/Marten/MartenPersistence.cs, next to the Todos' line:

csharp
opts.Schema.For<Project>().MultiTenanted();

Marten, with accounts, without organisations

Marten creates the table when the app starts, so there's no migration. Index the owner, so listing a user's projects stays fast, in src/ApiHost/Data/Marten/MartenPersistence.cs:

csharp
opts.Schema.For<Project>().Index(x => x.OwnerId);

Marten, without accounts

Marten creates the table when the app starts: there's nothing to add.

EF Core

Add a DbSet for it to src/ApiHost/Data/EfCore/AppDbContext.cs, next to the Todos':

csharp
public DbSet<Project> Projects => Set<Project>();

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 projects stays fast:

csharp
modelBuilder.Entity<Project>().HasIndex(p => p.OwnerId);

Then add a migration. The app applies it when it starts, here and in production.

Tutorial: step 1, The data.

Describe the requests ​

For each request with a body, add a record, and a FluentValidation validator for it. Wolverine runs the validator before the endpoint, and answers an invalid request with 400 Bad Request and the errors, which the client's forms show next to their fields.

csharp
public record CreateProject(string Name);

public class CreateProjectValidator : AbstractValidator<CreateProject>
{
    public CreateProjectValidator() => RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
}

Only the fields in the record can be set, so a request can't change what it shouldn't.

Tutorial: step 2, The request and its validation.

Add the endpoints ​

An endpoint is a static method with a route attribute, such as [WolverineGet("/api/projects")] or [WolverinePost("/api/projects")]. Wolverine passes in what its parameters ask for: the request body, the database session, the signed-in user, and route values such as {id}.

With accounts

Add [Authorize] to each, so only signed-in users can call it. For something that isn't the caller's, answer 404 Not Found, as for something that doesn't exist, so nobody can find out which ids exist.

The first value an endpoint returns is the response; any after it are messages to send. Wolverine saves the changes and the messages in one transaction, so a message is sent only if the change was saved, and is delivered even if the app stops straight afterwards.

Tutorial: step 4, The endpoints.

Do slow work in the background ​

Anything slow or unreliable that follows from a request (an email, a call to another service) goes in a message handler, not the endpoint. Return a message from the endpoint, such as ProjectCreated, and handle it in a class whose name ends in Handler:

csharp
public class ProjectCreatedHandler
{
    public static void Handle(ProjectCreated message, ILogger<ProjectCreatedHandler> logger)
        => logger.LogInformation("Project {ProjectId} was created", message.ProjectId);
}

It runs from a durable queue in PostgreSQL: if it fails it's retried, and if the app stops, it runs after the restart.

Tutorial: steps 3 and 5, Messages and Background work.

Send live updates ​

To refresh open tabs when the data changes, add a message with a name browsers know it by, [MessageIdentity("projects-changed")], and route it to SignalR in src/ApiHost/Program.cs:

csharp
opts.PublishMessage<ProjectsChanged>().ToSignalR();

With organisations

Send it to the organisation's group, ToWebSocketGroup(RealtimeGroups.Organisation(...)), so only its members get it (Realtime/RealtimeGroups.cs).

With accounts, without organisations

Send it to the owner's group, ToWebSocketGroup(RealtimeGroups.User(...)), so only their tabs get it (Realtime/RealtimeGroups.cs).

Without accounts

Every connected browser gets it.

Tutorial: step 3, Messages.

With accounts

Delete the data with its owner ​

With organisations

When an organisation is deleted, the app publishes OrganisationDeleted. Handle it to delete the organisation's projects, and add them to the organisation's data download (an IOrganisationDataSource, like Features/Todos/TodosOrganisationData.cs). Then nothing is left behind, and owners can take their data with them.

Without organisations

When an account is deleted, the app publishes AccountDeleted. Handle it to delete the user's projects, and add them to the user's data download (an IPersonalDataSource, like Features/Todos/TodosPersonalData.cs). Privacy laws give people both rights.

Each handler of these messages commits and retries on its own, so a failure in yours doesn't undo the others' work.

Tutorial: step 5, Background work.

Update the client's API types ​

With the API running, update the client's types from its OpenAPI document:

bash
cd src/Client
npm run gen:api

The client's calls to your endpoints are then checked by TypeScript.

Tutorial: step 7, The client's API types.

Add the page ​

  1. Queries: in a folder, src/Client/src/features/projects/, add TanStack Query hooks that call your endpoints, and refresh them when a live update arrives (useRealtime, in lib/realtime.ts).
  2. The page: a component in the same folder, built from the components in components/ui/.
  3. Its route: a route module in src/Client/src/routes/, which sets the page's title in its handle. Add index: true only if search engines should list the page; it's then also pre-rendered.
  4. With accounts Its URL: add it to src/Client/src/routes.ts, inside the require-auth layout if it needs a signed-in user, and to src/Client/src/pages.ts. A unit test checks the two agree.
  5. With accounts A link: in src/Client/src/features/account/AccountNavigation.tsx.
  6. Without accounts Its URL: add it to src/Client/src/routes.ts and src/Client/src/pages.ts. A unit test checks the two agree.
  7. Without accounts A link: in src/Client/src/App.tsx.

Tutorial: steps 8 and 9, Queries and The page.

Test it ​

  • With accounts, with the tests API tests in tests/ApiHost.Tests: that the endpoints work, that invalid requests are refused, and that nobody else can see or change the data.
  • Without accounts, with the tests API tests in tests/ApiHost.Tests: that the endpoints work, and that invalid requests are refused.
  • A client test next to the page, with the API faked by MSW.
  • With the tests The page in the accessibility checks: add its path to tests/e2e/specs/accessibility.spec.ts.

Then run them all, as Testing describes, and try the page in the browser.

Tutorial: step 10, Tests.

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