Skip to content

2. Validate author names with Cratis Arc

Reject blank and duplicate author names before saving them, then show the librarian why registration failed. In Cratis Arc, a validator on AuthorName checks the value itself; a validator on RegisterAuthor checks whether that name already exists. A database constraint protects uniqueness when two registrations race.

Continue with the files and imports from chapter 1. On C#, put each validator in its own file under src/Authors/ with namespace Library.Authors;; choose the same database branch. On the JVM, put each validator in its own file in the same package as the command and mark it @Component so Spring registers it. On TypeScript, put the validators under the Features/ root used by both discover() and the generator; regenerate the metadata so the host discovers them. Name comparison is exact in this lesson, not case-folded or normalized.

A blank name is invalid without consulting the database. Put that rule on the AuthorName concept, the type that wraps the name’s underlying string, so commands carrying it share the rule instead of declaring it separately.

Write a ConceptValidator for the value type. On C#, it applies FluentValidation rules to the concept’s underlying Value. The JVM implementation reads that value through value(), while TypeScript targets name.value with notEmpty():

public class AuthorNameValidator : ConceptValidator<AuthorName>
{
public AuthorNameValidator()
{
RuleFor(x => x.Value).NotEmpty().WithMessage("An author needs a name.");
}
}

View C# snippet source on GitHub

C# discovers the validator by convention; you do not register it manually. Spring registers the JVM validator through @Component. On TypeScript, regenerate metadata and restart the host to discover the decorated validator under Features/. The command pipeline then rejects a blank AuthorName before calling the handler.

Reject the duplicate against existing state

Section titled “Reject the duplicate against existing state”

A nonblank name can still duplicate an existing author. Use a CommandValidator for this rule: it validates the registration request and can use a database dependency to check existing state.

The validator asks the database whether an author already carries this name and rejects the command if one exists:

public class RegisterAuthorValidator : CommandValidator<RegisterAuthor>
{
public RegisterAuthorValidator(IMongoCollection<Author> authors)
{
RuleFor(c => c.Name)
.MustAsync(async (name, _) => !await authors.Find(a => a.Name == name).AnyAsync())
.WithMessage("An author with that name is already registered.");
}
}

View C# snippet source on GitHub

C# awaits the database lookup in FluentValidation’s MustAsync predicate. The JVM validator awaits its repository in the suspending validate function; its shared fluent rules do not support asynchronous predicates. TypeScript uses mustAsync and resolves the application-owned AuthorRepository token from currentServices() inside the rule. Keep that resolution there: validators are constructed during host preflight, before a tenant exists, so constructor-injecting the tenant-scoped MongoDB repository would fail startup.

Keep the handler’s chapter-1 write unchanged. The validator runs first; if it fails, Handle() on C# or handle on the JVM and TypeScript never executes.

On the relational branch, the .NET validator injects the context instead of the collection. The JVM and TypeScript validators still ask their repository; its persistence implementation supplies the relational lookup:

public class RegisterAuthorValidator : CommandValidator<RegisterAuthor>
{
public RegisterAuthorValidator(LibraryDbContext db)
{
RuleFor(c => c.Name)
.MustAsync(async (name, ct) => !await db.Authors.AnyAsync(a => a.Name == name, ct))
.WithMessage("An author with that name is already registered.");
}
}

View C# snippet source on GitHub

A check-then-write has a race: two registrations can both pass validation. The validator supplies the friendly message; the database must enforce uniqueness independently.

In the .NET host, add the following block to Program.cs after app.UseCratisArc() and before RunAsync(). On the JVM, add the Spring AuthorIndexes component after declaring Author, with MongoTemplate on the classpath; its constructor installs the unique index at startup. On TypeScript, after registering the artifacts, repository, and MongoDB in the standalone host, replace that host’s builder.build() / app.run() lines with await startWithAuthorIndex(builder). The helper creates a scope for tenant default, resolves its MongoCollection<Author>, installs the index, disposes the scope, then runs the host. The Arc validators do not create indexes:

using (var scope = app.Services.CreateScope())
{
var authors = scope.ServiceProvider.GetRequiredService<IMongoCollection<Author>>();
await authors.Indexes.CreateOneAsync(new CreateIndexModel<Author>(
Builders<Author>.IndexKeys.Ascending(author => author.Name),
new CreateIndexOptions { Unique = true, Name = "unique_author_name" }));
}

View C# snippet source on GitHub

Restart the host and require index creation to succeed. Existing duplicate names must be resolved first; do not ignore an index-creation failure. The C# and TypeScript examples resolve stored field names through their serializers rather than guessing them; the Spring Data example uses its mapped name property.

Keep the React form from chapter 1. After proxy regeneration, the C# and TypeScript generators include the concept’s portable notEmpty rule in the frontend validator. CommandDialog can then disable confirmation for a blank name without a server round trip.

The uniqueness check still needs the database. When the server rejects a duplicate, the generated proxy returns the validation result and CommandDialog displays “An author with that name is already registered.” against the name field.

This is a fragment of AddAuthor from chapter 1; retain its imports and per-operation const [id] = useState(() => Guid.create()) initialization. Mount a new dialog instance for each registration.

AddAuthor.tsx — form fragment
<CommandDialog<RegisterAuthor> command={RegisterAuthor} title="Add author" okLabel="Add" initialValues={{ id }}>
<InputTextField<RegisterAuthor> value={i => i.name} title="Name" />
</CommandDialog>

Regenerate validation metadata with dotnet build -c Debug on C#, ./gradlew generateArcProxies on the JVM, or npm run generate on TypeScript. Restart the backend with the validators and database constraint in place, then run the frontend type-check/build.

Open a new dialog and leave Name blank. On C# and TypeScript, confirmation should stay disabled. On the JVM, expect a server rejection when submitting the imperative validator example; confirmation is disabled locally only if you also declared the fluent browser rule described above.

Submit a new name successfully, then open another dialog and submit that exact name again. Expect a server validation message and no additional row. Confirm index creation or schema application succeeded separately: a friendly duplicate rejection alone does not prove concurrency protection.

Author registration now checks the name before writing, reports validation failures in the existing form, and relies on the database constraint to prevent concurrent duplicates. These are separate checks: the validator explains a rejection to the librarian; the constraint protects stored data.

Keep this project for adding books →. The next chapter gives each book an author id and uses it to read that author’s catalog.