The user wants a design for a "Dynamic Form Builder Backend".
Key requirements:
OOP Aggregates: This implies Domain-Driven Design (DDD). I need to identify the core aggregates (e.g., Form, Submission).
Validation Strategy Objects: The form fields have dynamic validation rules. Instead of hardcoded if/else, I should use the Strategy pattern where each validation type (Required, MinLength, Regex) is a separate strategy object.
Event Sourcing: The state of the aggregates shouldn't just be overwritten. Every change (FormCreated, FieldAdded, SubmissionReceived) should be stored as an event, and the state rebuilt by replaying these events.
High-Level Architecture:
Domain Layer: The core business logic.
Aggregates: Form (definition), FormSubmission (user data).
Entities/Value Objects: Field (name, type, validation rules), ValidationRule.
Events: FormCreated, FieldAdded, FormSubmitted, etc.
Services: FormBuilder, SubmissionHandler.
Application Layer: Use cases / Command Handlers.
Infrastructure Layer: Persistence (Event Store), API controllers.
Detailed Design Steps:
The "Form" Aggregate:
A Form is a collection of Fields.
Fields have types (Text, Number, Email) and validation rules.
Invariants: Cannot have two fields with the same ID. Cannot submit if form is archived? (Keep it simple for now).
ValidationContext: Holds the field value and the configuration.
ValidationResult: Valid/Invalid + errors.
The Aggregate Root (FormAggregate):
State: id, fields, version.
Command: addField(fieldConfig).
Event generated: FieldDefinitionAdded.
Refining the "Dynamic" part:
The form structure isn't known at compile time. The backend receives a schema (JSON-like).
The FormAggregate stores the schema.
The Submission process validates incoming data against that schema using the strategies.
Self-Correction/Refinement during thought process:
Initial thought: Should FormSubmission be a separate Aggregate?
Refinement: Yes. A Form might have millions of submissions. Loading the Form aggregate just to add a submission is okay, but usually, the Submission is its own lifecycle entity linked to a Form definition. However, to demonstrate Event Sourcing effectively on one stream, I might treat the Form Definition and Submissions as separate streams.
Better approach for this prompt:
Form Definition Aggregate: Manages the structure and validation rules.
Submission Process: Takes the Form Definition (read model or replayed) and validates the data. For Event Sourcing, the "Submission" itself is an event appended to a specific stream (e.g., form-{id}-submissions) or just a generic event bus.
Decision: Let's focus the Event Sourcing example on the Form Definition lifecycle (creating, editing fields) as that's the most complex aggregate behavior. I will also show how a submission is validated against the reconstructed state.
Structure of the response:
Architecture Overview: Explain the DDD and Event Sourcing concepts used.
Domain Models (The Aggregates): Define Form and Field.
Validation Strategies: The Strategy pattern implementation.
Event Sourcing Implementation: The Events, the Store, and the Aggregate re-hydration logic.
Usage Example: A script showing how to create a form, add a field, and validate data.
type Event = { type: string, timestamp: Date, payload: any };
Aggregate:
Needs version for optimistic concurrency.
Needs uncommittedChanges.
Let's write the code. (I will produce TypeScript code as it balances type safety with readability for this kind of architecture).
Constraint Check: The user asked for "OOP Aggregates". I must ensure the Form class holds state and logic, not just a data bucket.
Constraint Check: "Validation Strategy Objects". I need a ValidationStrategyRegistry to decouple the validation logic from the field types.
Final Polish:
Ensure the distinction between the "Write Model" (Aggregates) and the "Read Model" (implied) is clear, even if I don't implement a full projection engine, I should mention it. The focus is the backend construction.
Let's organize the code blocks.
Events & Contracts
Validation Strategies
The Aggregate Root (Form)
The Repository & Event Store
Execution/Service Layer
(Self-Correction on Validation): The prompt asks for validation strategy objects. When a user submits a form, the system needs to look up the form definition, iterate over its fields, find the corresponding strategy for each validation rule (e.g., "min:5"), and execute it.
Let's go.
This design implements a backend for a Dynamic Form Builder using Domain-Driven Design (DDD). It separates the concerns of data structure (The Form), business logic (Validation), and state management (Event Sourcing).
Architecture Overview
Domain Layer: Contains the Aggregates (Form, FormSubmission) and Value Objects.
Strategy Pattern: Decouples validation rules (e.g., Regex, Required, Range) from the domain entities.
Event Sourcing: Instead of storing just the current state, we store a sequence of events (FormCreated, FieldAdded, SubmissionReceived) to rebuild the aggregate state.
Application Layer: Services that handle commands and dispatch events.
1. The Core Domain & Events
First, we define the "facts" that happen to our system. These are immutable.
typescript
// Core Types
type UUID = string;
type FieldConfig = Record<string, any>;
// Events (The source of truth)
interface DomainEvent {
eventId: UUID;
occurredAt: Date;
aggregateId: UUID;
}
class FormCreated implements DomainEvent {
constructor(
public readonly eventId: UUID,
public readonly aggregateId: UUID,
public readonly occurredAt: Date,
public readonly title: string
) {}
}
class FieldAddedToForm implements DomainEvent {
constructor(
public readonly eventId: UUID,
public readonly aggregateId: UUID,
public readonly occurredAt: Date,
public readonly fieldId: UUID,
public readonly type: string, // e.g., 'text', 'email', 'number'
public readonly label: string,
public readonly validators: ValidatorConfig[] // Storing strategy configs
) {}
}
class FormSubmitted implements DomainEvent {
constructor(
public readonly eventId: UUID,
public readonly aggregateId: UUID,
public readonly occurredAt: Date,
public readonly payload: Record<string, any>
) {}
}
2. Validation Strategy Objects
We use the Strategy Pattern to handle different validation types. The form definition stores the configuration for these strategies, and the backend instantiates the concrete strategy during execution.
typescript
// 1. The Strategy Interface
interface IValidationStrategy {
validate(value: any, fieldName: string): string | null; // Returns error message or null
}
// 2. Configuration DTO (stored in the Aggregate)
interface ValidatorConfig {
type: string;
params?: any;
message?: string;
}
// 3. Concrete Strategies
class RequiredStrategy implements IValidationStrategy {
constructor(private customMsg?: string) {}
validate(value: any, fieldName: string): string | null {
if (value === null || value === undefined || value === '') {
return this.customMsg || `${fieldName} is required.`;
}
return null;
}
}
class RegexStrategy implements IValidationStrategy {
constructor(private pattern: string, private customMsg?: string) {}
validate(value: any, fieldName: string): string | null {
const regex = new RegExp(this.pattern);
if (!regex.test(String(value))) {
return this.customMsg || `${fieldName} format is invalid.`;
}
return null;
}
}
class RangeStrategy implements IValidationStrategy {
constructor(private min: number, private max: number) {}
validate(value: any, fieldName: string): string | null {
const num = Number(value);
if (isNaN(num) || num < this.min || num > this.max) {
return `${fieldName} must be between ${this.min} and ${this.max}.`;
}
return null;
}
}
// 4. Factory to create strategies from config
class ValidationStrategyFactory {
static create(config: ValidatorConfig): IValidationStrategy {
switch(config.type) {
case 'REQUIRED':
return new RequiredStrategy(config.message);
case 'REGEX':
return new RegexStrategy(config.params.pattern, config.message);
case 'RANGE':
return new RangeStrategy(config.params.min, config.params.max);
default:
throw new Error(`Unknown validator type: ${config.type}`);
}
}
}
3. The Aggregate Root (OOP Aggregate)
The FormAggregate is the consistency boundary. It maintains the state of the Form definition. It does not have setters; it applies events to mutate its internal state.
typescript
// Value Object representing a Field Definition
class FormField {
constructor(
public readonly id: UUID,
public readonly type: string,
public readonly label: string,
public readonly validators: ValidatorConfig[]
) {}
}
// The Aggregate Root
class FormAggregate {
private _id: UUID;
private _title: string = "";
private _fields: Map<UUID, FormField> = new Map();
private _version: number = 0; // For optimistic concurrency
// State reconstruction
get id(): UUID { return this._id; }
get fields(): FormField[] { return Array.from(this._fields.values()); }
constructor(events: DomainEvent[] = []) {
// Event Sourcing: Rebuild state by replaying history
events.forEach(event => this.apply(event));
}
// Command: Add a field
public static create(id: UUID, title: string): FormAggregate {
const form = new FormAggregate();
// Trigger event
const event = new FormCreated(uuid(), id, new Date(), title);
form.apply(event);
return form;
}
// Command: Add Field
public addField(type: string, label: string, validators: ValidatorConfig[]): void {
// Invariant checks could go here (e.g., max 50 fields)
const fieldId = uuid();
const event = new FieldAddedToForm(uuid(), this._id, new Date(), fieldId, type, label, validators);
this.apply(event);
}
// Business Logic: Validate incoming data payload
public validateSubmission(payload: Record<string, any>): { valid: boolean; errors: Record<string, string[]> } {
const errors: Record<string, string[]> = {};
for (const field of this.fields) {
const value = payload[field.id];
const fieldErrors: string[] = [];
// Iterate over configured strategies
for (const config of field.validators) {
const strategy = ValidationStrategyFactory.create(config);
const error = strategy.validate(value, field.label);
if (error) fieldErrors.push(error);
}
if (fieldErrors.length > 0) {
errors[field.id] = fieldErrors;
}
}
return {
valid: Object.keys(errors).length === 0,
errors
};
}
// The Apply method: The heart of Event Sourcing
private apply(event: DomainEvent): void {
if (event instanceof FormCreated) {
this._id = event.aggregateId;
this._title = event.title;
} else if (event instanceof FieldAddedToForm) {
this._fields.set(event.fieldId, new FormField(
event.fieldId,
event.type,
event.label,
event.validators
));
}
this._version++;
}
}
4. Application Service (Wiring it together)
This service acts as the facade. It loads events from the database, reconstitutes the aggregate, executes logic, and saves new events.
typescript
// Mock Database (Event Store)
interface IEventStore {
loadStream(aggregateId: UUID): DomainEvent[];
append(aggregateId: UUID, events: DomainEvent[]): void;
}
class FormApplicationService {
constructor(private store: IEventStore) {}
// Use Case: Define a new form structure
public createForm(command: { title: string }): UUID {
const id = uuid();
const form = FormAggregate.create(id, command.title);
// Extract uncommitted events and save
// (In a real app, the aggregate tracks new events separately from history)
const newEvent = new FormCreated(uuid(), id, new Date(), command.title);
this.store.append(id, [newEvent]);
return id;
}
// Use Case: Add a field with validation strategies
public addFieldToForm(command: {
formId: UUID,
type: string,
label: string,
validators: ValidatorConfig[]
}): void {
const history = this.store.loadStream(command.formId);
const form = new FormAggregate(history);
form.addField(command.type, command.label, command.validators);
// Persist new event (simulated)
// In reality, the aggregate would return the event object to append
const newEvent = new FieldAddedToForm(
uuid(), command.formId, new Date(), uuid(), command.type, command.label, command.validators
);
this.store.append(command.formId, [newEvent]);
}
// Use Case: Submit data
public submitForm(command: { formId: UUID, payload: Record<string, any> }): { success: boolean; errors?: any } {
// 1. Reconstitute Aggregate
const history = this.store.loadStream(command.formId);
const form = new FormAggregate(history);
if (form.fields.length === 0) throw new Error("Form has no fields defined.");
// 2. Execute Validation Strategies
const result = form.validateSubmission(command.payload);
if (!result.valid) {
return { success: false, errors: result.errors };
}
// 3. Create Success Event
const submissionEvent = new FormSubmitted(uuid(), command.formId, new Date(), command.payload);
this.store.append(command.formId, [submissionEvent]);
return { success: true };
}
}
5. Example Usage
Here is how the client code consumes this backend.
Extensibility: To add a new validation type (e.g., UniqueEmailStrategy which checks a database), you simply implement IValidationStrategy and add a case to the ValidationStrategyFactory. The FormAggregate code does not need to change (Open/Closed Principle).
Auditability: Because we used Event Sourcing, we have a complete history of how the form definition changed over time and exactly who submitted what and when.
Consistency: The FormAggregate ensures that all validation rules are applied atomically against the specific version of the form structure defined at that moment.