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.
Validate the value, once
Section titled “Validate the value, once”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."); }}@Componentpublic final class AuthorNameValidator implements FundamentalsConceptValidator<AuthorName> { @Override public Class<AuthorName> getConceptType() { return AuthorName.class; }
@Override public List<ValidationResult> validate(AuthorName concept) { return concept.value().isBlank() ? List.of(ValidationResult.error("An author needs a name.")) : List.of(); }}@Componentclass AuthorNameValidator : FundamentalsConceptValidator<AuthorName> { override val conceptType: Class<AuthorName> = AuthorName::class.java
override fun validate(concept: AuthorName): List<ValidationResult> = if (concept.value().isBlank()) { listOf(ValidationResult.error("An author needs a name.")) } else { emptyList() }}import { ConceptValidator, validator } from '@cratis/arc.core';
@validator(AuthorName)export class AuthorNameValidator extends ConceptValidator<AuthorName> { constructor() { super(); this.ruleFor(name => name.value).notEmpty().withMessage('An author needs a name.'); }}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."); }}public final class RegisterAuthorValidator implements BlockingCommandValidator<RegisterAuthor> { private final AuthorRepository authors;
public RegisterAuthorValidator(AuthorRepository authors) { this.authors = authors; }
@Override public Class<RegisterAuthor> getCommandType() { return RegisterAuthor.class; }
// validate has no coroutine in its signature, so the blocking lookup is called // directly. Reach for AsyncCommandValidator when the lookup itself is asynchronous. @Override public List<ValidationResult> validate(RegisterAuthor command, CommandContext context) { return authors.existsByName(command.name()) ? List.of(ValidationResult.error( "An author with that name is already registered.", List.of("name"))) : List.of(); }}
@Configurationpublic class RegisterAuthorValidation { @Bean public CommandValidator<RegisterAuthor> registerAuthorValidator(AuthorRepository authors) { return new BlockingCommandValidatorAdapter<>(new RegisterAuthorValidator(authors)); }}@Componentclass RegisterAuthorValidator( private val authors: AuthorRepository) : CommandValidator<RegisterAuthor> { override val commandType: Class<RegisterAuthor> = RegisterAuthor::class.java
// validate suspends, so the lookup is awaited directly. override suspend fun validate( command: RegisterAuthor, context: CommandContext ): List<ValidationResult> = if (authors.existsByName(command.name)) { listOf( ValidationResult.error( "An author with that name is already registered.", listOf("name") ) ) } else { emptyList() }}import { CommandValidator, currentServices, validator } from '@cratis/arc.core';
@validator(RegisterAuthor)export class RegisterAuthorValidator extends CommandValidator<RegisterAuthor> { constructor() { super(); this.ruleFor(command => command.name) .mustAsync(async (_name, command, signal) => { const authors = await currentServices().resolve(AuthorRepository); return !await authors.existsByName(command.name, signal); }) .withMessage('An author with that name is already registered.'); }}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."); }}public final class RegisterAuthorValidator implements BlockingCommandValidator<RegisterAuthor> { private final AuthorRepository authors;
public RegisterAuthorValidator(AuthorRepository authors) { this.authors = authors; }
@Override public Class<RegisterAuthor> getCommandType() { return RegisterAuthor.class; }
// validate has no coroutine in its signature, so the blocking lookup is called // directly. Reach for AsyncCommandValidator when the lookup itself is asynchronous. @Override public List<ValidationResult> validate(RegisterAuthor command, CommandContext context) { return authors.existsByName(command.name()) ? List.of(ValidationResult.error( "An author with that name is already registered.", List.of("name"))) : List.of(); }}
@Configurationpublic class RegisterAuthorValidation { @Bean public CommandValidator<RegisterAuthor> registerAuthorValidator(AuthorRepository authors) { return new BlockingCommandValidatorAdapter<>(new RegisterAuthorValidator(authors)); }}@Componentclass RegisterAuthorValidator( private val authors: AuthorRepository) : CommandValidator<RegisterAuthor> { override val commandType: Class<RegisterAuthor> = RegisterAuthor::class.java
// validate suspends, so the lookup is awaited directly. override suspend fun validate( command: RegisterAuthor, context: CommandContext ): List<ValidationResult> = if (authors.existsByName(command.name)) { listOf( ValidationResult.error( "An author with that name is already registered.", listOf("name") ) ) } else { emptyList() }}import { CommandValidator, currentServices, validator } from '@cratis/arc.core';
@validator(RegisterAuthor)export class RegisterAuthorValidator extends CommandValidator<RegisterAuthor> { constructor() { super(); this.ruleFor(command => command.name) .mustAsync(async (_name, command, signal) => { const authors = await currentServices().resolve(AuthorRepository); return !await authors.existsByName(command.name, signal); }) .withMessage('An author with that name is already registered.'); }}Install the database constraint
Section titled “Install the database constraint”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" }));}@Componentclass AuthorIndexes { AuthorIndexes(MongoTemplate template) { template.indexOps(Author.class) .createIndex(new Index().on("name", Sort.Direction.ASC).unique()); }}@Componentclass AuthorIndexes(template: MongoTemplate) { init { template.indexOps(Author::class.java) .createIndex(Index().on("name", Sort.Direction.ASC).unique()) }}import { Severity, type ArcApplicationBuilder } from '@cratis/arc.core';import { mongoCollection, type MongoCollection } from '@cratis/arc.mongodb';
export async function ensureAuthorNameIndex(collection: MongoCollection<Author>): Promise<void> { await collection.native.createIndex( { [collection.codec.fieldName('name')]: 1 }, { unique: true, name: 'unique_author_name' });}
// In start(), call startWithAuthorIndex(builder) instead of its build/run lines.export async function startWithAuthorIndex(builder: ArcApplicationBuilder): Promise<void> { const app = await builder.build(); try { const scope = app.server.services.createScope({ tenantId: 'default', correlationId: crypto.randomUUID(), principal: undefined, signal: new AbortController().signal, allowedSeverity: Severity.Warning }); try { await ensureAuthorNameIndex(await scope.resolve(mongoCollection(Author))); } finally { await scope.dispose(); } await app.run({ port: 3000 }); } finally { await app.dispose(); }}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.
Install a unique constraint on the stored author name. On .NET merge the override into your existing LibraryDbContext (do not declare it twice); on the JVM replace the AuthorRow mapping from the relational slice with the constrained version. On TypeScript, define your Drizzle authors table with the constrained version shown here (or add .unique() to your chapter-1 table) and apply the updated SQL schema before accepting writes; the EF Core override does not configure it.
public class LibraryDbContext : DbContext{ public DbSet<Author> Authors => Set<Author>();
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Author>().HasIndex(author => author.Name).IsUnique(); }}@Entity@Table(name = "authors", uniqueConstraints = @UniqueConstraint(name = "unique_author_name", columnNames = "name"))class AuthorRow { @Id UUID id; @Column(name = "name", nullable = false) String name; protected AuthorRow() {} AuthorRow(UUID id, String name) { this.id = id; this.name = name; }}@Entity@Table(name = "authors", uniqueConstraints = [UniqueConstraint(name = "unique_author_name", columnNames = ["name"])])class AuthorRow( @field:Id var id: UUID = UUID(0, 0), @field:Column(name = "name", nullable = false) var name: String = "")import { sqliteTable, text } from 'drizzle-orm/sqlite-core';import { DrizzleDialect, guidCodec, sqliteColumn } from '@cratis/arc.drizzle';
export const authors = sqliteTable('authors', { id: sqliteColumn(guidCodec(DrizzleDialect.SQLite))('id').primaryKey(), name: text('name').notNull().unique()});For the disposable SQLite tutorial database, stop the host, remove only Library/library.db, and restart so EnsureCreatedAsync creates the new schema. This loses tutorial data; re-register the authors afterward. For retained data, create/apply a migration instead. EnsureCreatedAsync never upgrades an existing database.
The UI already knows
Section titled “The UI already knows”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.
<CommandDialog<RegisterAuthor> command={RegisterAuthor} title="Add author" okLabel="Add" initialValues={{ id }}> <InputTextField<RegisterAuthor> value={i => i.name} title="Name" /></CommandDialog>Verify the rejection paths
Section titled “Verify the rejection paths”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.
What you built
Section titled “What you built”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.