We are going to design a dynamic form builder backend using:
- OOP aggregates: We'll have a Form aggregate that encapsulates form logic and state.
- Validation strategy objects: We'll have a validation system that supports multiple validation strategies (e.g., required, email, etc.) and can be extended.
- Event sourcing: We'll store events for every state change in the form (e.g., FormCreated, FieldAdded, etc.) and rebuild the current state from events.
Steps:
- Define the events that can happen in the form's lifecycle.
- Define the Form aggregate that will handle commands and emit events.
- Define the validation strategy pattern for field validation.
- Define a repository that can store and retrieve the aggregate by replaying events.
Let's break it down:
Events:
- FormCreated(formId, name, description)
- FieldAdded(fieldId, formId, fieldType, label, validationRules, order)
- FieldUpdated(fieldId, formId, fieldType, label, validationRules, order) [optional, but we might want to update field properties]
- FieldRemoved(fieldId, formId)
- FormPublished(formId) [if we want a published state]
However, to keep it simple, we might only have:
- FormCreated
- FieldAdded
- FieldRemoved
But note: if we remove a field and then add it again, we might want to keep the same fieldId? We'll assume fieldId is generated when the field is added and remains until removed.
We might also want to update a field? Let's assume we can update a field (without removing) and we emit FieldUpdated.
So events:
FormCreated
FieldAdded
FieldUpdated
FieldRemoved
We'll also need a way to reconstruct the form from events.
Aggregate: Form
- id: FormId (value object)
- name: string
- description: string
- fields: list of Field (each field has id, type, label, validationRules, order)
- isPublished: boolean (optional)
The aggregate will have methods that correspond to commands (e.g., addField, updateField, removeField, publish) and these methods will validate the command (business rules) and then emit the corresponding event.
Validation strategy for fields:
We'll have a FieldValidator that uses a list of ValidationRule (strategy pattern) for each field.
ValidationRule interface:
validate(value: any): boolean or { valid: boolean, message: string }
Then we can have:
RequiredRule
EmailRule
MinLengthRule
MaxLengthRule
etc.
The FieldValidator will take a list of rules and run them in order.
However, note: the validation rules are part of the field's definition (metadata) and are stored in the event. So when we rebuild the form from events, we need to reconstruct the Field objects with their validation rules.
But: how do we store the validation rules in the event? We can store them as a list of rule types and parameters. For example:
{ type: 'required' }
{ type: 'email' }
{ type: 'minLength', value: 5 }
Then when we rebuild the field, we need to convert these rule configurations into actual rule objects. We can do that by having a ValidationRuleFactory that creates the rule objects from the configuration.
Alternatively, we can store the validation rules as a list of strings (like JSON) and then when building the field, we parse them. But we want to avoid storing implementation-specific classes in events? Actually, event sourcing typically stores the event data in a way that is serializable (e.g., JSON). So we can store the rule configuration as a dictionary (or a list of dictionaries) and then when building the field, we convert to rule objects.
However, note that the validation rules might be complex and we might want to version them. So we can store the rule type and parameters and then have a factory that maps type to a rule class.
Let's design:
ValidationRule (interface)
validate(value, context?): ValidationResult
ValidationResult: { valid: boolean, message?: string }
Then we have concrete rules:
class RequiredRule implements ValidationRule {
validate(value) {
if (value === undefined || value === null || value === '') {
return { valid: false, message: 'This field is required' };
}
return { valid: true };
}
}
But note: we want to support multiple rules and custom messages? We might want to allow the form builder to set a custom message for a rule? Then we can extend the rule configuration to have a message.
Example rule configuration for a field:
[
{ type: 'required', message: 'Please fill out this field' },
{ type: 'email', message: 'Please enter a valid email' },
{ type: 'minLength', value: 5, message: 'Must be at least 5 characters' }
]
Then when building the field, we create:
class Field {
id: string
type: string
label: string
validationRules: ValidationRule[]
order: number
constructor(id, type, label, validationRulesConfig, order) {
this.id = id;
this.type = type;
this.label = label;
this.validationRules = validationRulesConfig.map(config => ValidationRuleFactory.create(config));
this.order = order;
}
validate(value) {
for (const rule of this.validationRules) {
const result = rule.validate(value);
if (!result.valid) {
return result;
}
}
return { valid: true };
}
}
And the ValidationRuleFactory:
class ValidationRuleFactory {
static create(config) {
switch (config.type) {
case 'required': return new RequiredRule(config.message);
case 'email': return new EmailRule(config.message);
case 'minLength': return new MinLengthRule(config.value, config.message);
// ... etc.
default: throw new Error(`Unknown validation rule type: ${config.type}`);
}
}
}
But note: we might have custom rules? Then we need to allow registration of custom rules. We can have a registry:
class ValidationRuleRegistry {
private rules: Map<string, new (config) => ValidationRule> = new Map();
register(type: string, ruleClass: new (config) => ValidationRule) {
this.rules.set(type, ruleClass);
}
create(config) {
const RuleClass = this.rules.get(config.type);
if (!RuleClass) {
throw new Error(`Unknown validation rule type: ${config.type}`);
}
return new RuleClass(config);
}
}
Then we can set the factory to use the registry.
However, for simplicity, let's assume we have a fixed set of rules and we don't need to extend at runtime. But in a real system, we might want to allow plugins. So let's design with a registry.
But note: when we replay events, we are in a different process (maybe) and we need to have the same rule classes available? Actually, the rule classes are part of the application code, so as long as we have the same codebase (or compatible) we can recreate them.
However, if we want to allow dynamic rule registration (like from a database of custom rules) then we need to store the rule implementation? That's too complex. Usually, event sourcing and CQRS are used with a fixed set of domain logic. So we assume the rule types are known and fixed.
Let's stick to a fixed set for now.
But note: the rule configuration might change? For example, we change the message of a rule? That's a field update event. So we store the new configuration.
Now, the Form aggregate:
class Form {
private formId: FormId;
private name: string;
private description: string;
private fields: Field[] = [];
private isPublished: boolean = false;
private version: number = 0;
// We'll have a constructor that takes the initial state for a new form? Actually, we create a form via a command and then apply the FormCreated event.
// Method to handle commands:
addField(command: AddFieldCommand) {
// Business rules:
// - form must not be published? (if published, we cannot change? That's a business rule)
// - field order must be unique? We can allow same order? Then we sort by order? Or we enforce unique order? Let's enforce unique order for simplicity.
// Check if there's already a field with the same order?
if (this.fields.some(f => f.order === command.order)) {
throw new Error('Field order must be unique');
}
// Create field from command
const field = new Field(
command.fieldId,
command.type,
command.label,
command.validationRules, // this is the config array
command.order
);
this.applyEvent(new FieldAddedEvent(this.formId, command.fieldId, command.type, command.label, command.validationRules, command.order));
}
updateField(command: UpdateFieldCommand) {
const fieldIndex = this.fields.findIndex(f => f.id === command.fieldId);
if (fieldIndex === -1) {
throw new Error('Field not found');
}
// Update the field? We can create a new Field object with updated properties? But note: the validation rules are part of the field. So we update the field's properties.
// However, we are storing the field as an array of Field objects. We can replace the field at the index with a new Field object? But note: the field might have other properties we are not updating? Actually, the command might only update some properties.
// Alternatively, we can have the Field class be mutable? But in event sourcing, we usually have immutable aggregates? Actually, the aggregate is mutable in memory but we apply events to change state. So we can update the field in place? But then when we replay events, we are creating new Field objects from the events.
// Let's think: when we apply the FieldUpdatedEvent, we will update the field in the aggregate's state. We can do:
const existingField = this.fields[fieldIndex];
const updatedField = new Field(
command.fieldId,
command.type ?? existingField.type,
command.label ?? existingField.label,
command.validationRules ?? existingField.validationRulesConfig, // but note: the Field class stores validationRules as objects, but we need to store the config in the event? Actually, the event stores the config (the array of rule configs). So when we create the Field, we pass the config and the Field constructor converts to rule objects.
// But wait: the existingField has validationRules (the array of ValidationRule objects). We need the config for the event? So we should store the config in the Field? Or we can convert the rule objects back to config? That's not straightforward.
// Alternatively, we can store in the Field the config (the array of rule configs) and then when we need to validate, we create the rule objects from the config? That way, the Field is immutable and only stores the config. Then every time we validate, we create the rules? That might be inefficient if we validate a lot.
// Let's change the Field design:
class Field {
id: string;
type: string;
label: string;
validationRulesConfig: any[]; // the raw config from the event
order: number;
constructor(id, type, label, validationRulesConfig, order) {
this.id = id;
this.type = type;
this.label = label;
this.validationRulesConfig = validationRulesConfig;
this.order = order;
}
validate(value) {
const rules = this.validationRulesConfig.map(config => ValidationRuleFactory.create(config));
for (const rule of rules) {
const result = rule.validate(value);
if (!result.valid) {
return result;
}
}
return { valid: true };
}
}
Then when we update a field, we can update the config? But the command might only update the label, so we keep the old validationRulesConfig.
So:
const updatedField = new Field(
command.fieldId,
command.type ?? existingField.type,
command.label ?? existingField.label,
command.validationRules ?? existingField.validationRulesConfig,
command.order ?? existingField.order
);
But note: the order might be updated? Then we need to check for duplicate order again.
However, we are updating the field, so the order might change. We must check if the new order is already taken by another field (excluding the current field).
Let's adjust:
const newOrder = command.order ?? existingField.order;
if (newOrder !== existingField.order) {
// Check if any other field has this order
if (this.fields.some(f => f.id !== command.fieldId && f.order === newOrder)) {
throw new Error('Field order must be unique');
}
}
Then we update the field at the index with the updatedField.
But note: the event we emit should have the updated field's config.
So:
this.applyEvent(new FieldUpdatedEvent(
this.formId,
command.fieldId,
updatedField.type,
updatedField.label,
updatedField.validationRulesConfig,
updatedField.order
));
}
removeField(command: RemoveFieldCommand) {
const fieldIndex = this.fields.findIndex(f => f.id === command.fieldId);
if (fieldIndex === -1) {
throw new Error('Field not found');
}
this.applyEvent(new FieldRemovedEvent(this.formId, command.fieldId));
}
// ... other methods
// When we apply an event, we update the state.
private applyEvent(event) {
// increment version?
this.version++;
switch (event.type) {
case 'FormCreated':
this.formId = event.formId;
this.name = event.name;
this.description = event.description;
break;
case 'FieldAdded':
const newField = new Field(
event.fieldId,
event.type,
event.label,
event.validationRules, // config array
event.order
);
this.fields.push(newField);
// sort by order? We might want to keep the fields sorted by order for rendering?
this.fields.sort((a, b) => a.order - b.order);
break;
case 'FieldUpdated':
const index = this.fields.findIndex(f => f.id === event.fieldId);
if (index !== -1) {
this.fields[index] = new Field(
event.fieldId,
event.type,
event.label,
event.validationRules,
event.order
);
this.fields.sort((a, b) => a.order - b.order);
}
break;
case 'FieldRemoved':
this.fields = this.fields.filter(f => f.id !== event.fieldId);
break;
case 'FormPublished':
this.isPublished = true;
break;
}
}
}
5. Repository: We store events in an event store. The repository will load the events for a form and then apply them to a new Form aggregate to rebuild the state.
class FormRepository {
async getById(formId: FormId): Promise {
const events = await this.eventStore.getEventsForAggregate(formId);
const form = new Form(); // We need a way to create an empty form and then apply events? Actually, the first event is FormCreated, so we can apply events from the beginning.
// We need to set the formId? Actually, the FormCreated event has the formId.
for (const event of events) {
form.applyEvent(event); // But note: the applyEvent method is private? We can make it public for the repository? Or we can have a method that replays events.
// Alternatively, we can have a static method that creates a form from events.
}
return form;
}
async save(form: Form) {
// We need to get the uncommitted events from the form? How does the form track events? We can have a list of uncommitted events in the form.
// In the Form aggregate, we can have:
// private uncommittedEvents: Event[] = [];
// Then in applyEvent, we push the event to uncommittedEvents and also change state.
// Then when saving, we get the uncommittedEvents, store them, and then clear the uncommittedEvents.
const events = form.getUncommittedEvents();
await this.eventStore.storeEvents(events);
form.clearUncommittedEvents();
}
}
6. Commands: These are the inputs from the outside (e.g., from a controller). They are simple data structures.
interface AddFieldCommand {
formId: string;
fieldId: string; // generated by the client? or by the server? We can generate on the server to avoid collisions? But in event sourcing, we can let the client generate the id if we want to avoid a round trip? Actually, the client can generate a UUID for the field.
type: string; // e.g., 'text', 'email', etc.
label: string;
validationRules: any[]; // array of rule configs
order: number;
}
Similarly for UpdateFieldCommand and RemoveFieldCommand.
- Event Store: We need to store events. The event store should store events for each aggregate (form) in order.
interface Event {
id: string; // event id (unique)
aggregateId: string; // formId
type: string; // event type (e.g., 'FieldAdded')
data: any; // the event data (without the type and aggregateId? Actually, we can store the whole event with metadata)
version: number; // the version of the aggregate after this event? Or the event's own version? We can have a sequence number per aggregate.
occurredAt: Date;
}
The event store must be able to store and retrieve events by aggregateId in order.
- Validation: When we submit a form (fill it with data), we want to validate the data against the form's fields.
We can have a FormValidator that takes a Form aggregate and a dictionary of field values (fieldId -> value) and then validates each field.
But note: the form might have fields that are not required and the user didn't fill? That's okay. We only validate the rules for the fields that are present? Actually, the required rule will fail if the value is missing.
So:
class FormValidator {
validate(form: Form, values: { [fieldId: string]: any }): { [fieldId: string]: ValidationResult[] } {
const errors: { [fieldId: string]: ValidationResult[] } = {};
for (const field of form.fields) {
const value = values[field.id];
const result = field.validate(value);
if (!result.valid) {
if (!errors[field.id]) {
errors[field.id] = [];
}
errors[field.id].push(result);
}
}
return errors;
}
}
9. Putting it together:
We have:
- Form aggregate (with uncommitted events)
- ValidationRule and Field (with validation)
- Commands and Events
- Repository and EventStore
- FormValidator for validating user input.
-
Additional considerations:
- We might want to support different field types (text, email, number, etc.) and each type might have its own validation? Actually, the validation rules are independent of the field type? But we can have a rule that only applies to a certain type? That's a business rule that we can enforce in the aggregate when adding a field? Or we can have a rule that validates the type? Actually, the form builder might have a set of allowed field types and each field type has a set of allowed validation rules? That's a UI concern? We might not enforce that in the backend? But we can.
However, for simplicity, we'll assume any field type can have any validation rule? But that doesn't make sense (e.g., minLength for a number? We can convert to string? Or we can have type-specific rules?).
Alternatively, we can have a FieldType class that knows which validation rules are allowed? But that might be overkill.
Let's leave it open: the form builder frontend will only allow certain rules for certain types, but the backend doesn't enforce that? Or we can have a rule that checks the type? Actually, the validation rule might depend on the value type. For example, MinLengthRule for a string, MinRule for a number.
So we can have:
class MinLengthRule implements ValidationRule {
constructor(private min: number, private message?: string) {}
validate(value) {
if (typeof value !== 'string') {
return { valid: false, message: 'Must be a string' };
}
if (value.length < this.min) {
return { valid: false, message: this.message ?? `Must be at least ${this.min} characters` };
}
return { valid: true };
}
}
But then we are mixing type validation and rule validation? Actually, the form builder might have a field type and then the value is expected to be of that type. We can have a TypeRule that ensures the value is of the correct type? Or we can do type coercion? We'll leave that to the frontend and the form validator will assume the value is already in the correct type? Actually, when we get the form data from the frontend, it's usually as strings (from input fields) unless we use a more complex UI.
So maybe we don't need to validate the type? The form builder might have a field type and then the frontend will render an appropriate input (e.g., number input) and then the value will be a string? Actually, the HTML input returns string. So we might want to convert the value to the expected type? Or we can have a rule that converts? That's getting complex.
Let's stick to string validation for now? But then email rule works on string, required on any, minLength on string? What about a number field? We can have a MinRule that works on numbers? But the value is a string. So we need to convert? We can do:
class MinRule implements ValidationRule {
constructor(private min: number, private message?: string) {}
Note: This is a high-level design and we are writing in TypeScript-like pseudocode.
We'll write:
- Events (as classes or interfaces? We can use classes for events so we can have a type property? Or we can have a discriminated union)
Let's use classes for events:
class FormCreatedEvent {
type = 'FormCreated';
constructor(public formId: string, public name: string, public description: string) {}
}
But then when we store, we might want to store the event as a plain object? We can have a toJSON method? Or we can store the event as is and then when retrieving, we reconstruct? We'll assume the event store stores the event as a JSON with a type field.
Alternatively, we can have:
interface Event {
type: string;
aggregateId: string;
data: any;
version: number;
occurredAt: Date;
}
And then we have concrete event classes that have a toJSON method that returns the data? But then we lose the class? We can store the class name? That's not good for versioning.
Alternatively, we can have a base class for events:
abstract class Event {
abstract type: string;
abstract aggregateId: string;
// other metadata? We can have a base class with version, occurredAt, etc.
toJSON() {
return {
type: this.type,
aggregateId: this.aggregateId,
data: this, // but then we have circular? Actually, we want to store the event data without the type and aggregateId? We can have:
// data: { ...this } but then we have the type and aggregateId in the data? We can have:
// { type, aggregateId, ...eventData }
};
}
}
But then when we store, we store the whole event? We can have:
eventStore.storeEvent({
id: eventId,
aggregateId: formId,
type: event.type,
data: event, // but then we have duplicate type? We can have the event's type and the data without the type? Actually, we can have:
});
This is getting messy.
Let's simplify: we store the event as a JSON object that has:
{
"id": "event-id",
"aggregateId": "form-id",
"type": "FieldAdded",
"data": {
"fieldId": "...",
"type": "...",
...
},
"version": 1,
"occurredAt": "2021-01-01T00:00:00.000Z"
}
Then when we load, we get an array of these objects. We then need to convert the data to the concrete event class? We can have a function that maps type to a class? But we don't need the class to apply the event? We can apply the event by having a switch on the type and then use the data.
So we don't need concrete event classes? We can have:
type Event = {
id: string;
aggregateId: string;
type: string;
data: any;
version: number;
occurredAt: Date;
}
And then in the Form aggregate, when applying an event:
applyEvent(event: Event) {
switch (event.type) {
case 'FormCreated':
this.formId = event.data.formId;
this.name = event.data.name;
this.description = event.data.description;
break;
case 'FieldAdded':
const field = new Field(
event.data.fieldId,
event.data.type,
event.data.label,
event.data.validationRules,
event.data.order
);
this.fields.push(field);
this.fields.sort((a, b) => a.order - b.order);
break;
// ... etc.
}
}
Then we don't need event classes? But then we lose type safety for the event data? We can have:
interface FormCreatedEventData {
formId: string;
name: string;
description: string;
}
and then in the switch:
case 'FormCreated':
const data = event.data as FormCreatedEventData;
...
That's acceptable.
But then when we emit an event from the aggregate, we need to create the event object. We can have:
this.uncommittedEvents.push({
id: uuid(),
aggregateId: this.formId,
type: 'FieldAdded',
data: {
fieldId: command.fieldId,
type: command.type,
label: command.label,
validationRules: command.validationRules,
order: command.order
},
version: this.version + 1, // but note: the version is the aggregate version after the event? We can set it when storing? Actually, the event store might assign the version? We can have the aggregate track the version and then when we apply the event, we increment the version? Then the event's version is the new version.
occurredAt: new Date()
});
And then in applyEvent, we set the aggregate's version to the event's version? Actually, the aggregate's version should be the version of the last event applied.
So:
applyEvent(event: Event) {
this.version = event.version;
// ... rest
}
But then when we create a new form, the first event (FormCreated) should have version 1? We can set the version to 1 in the FormCreated event? Then when we apply, we set this.version = event.version.
However, when we create a new form, we don't have a version? We can start at 0 and then after applying FormCreated, version becomes 1.
So:
let form = new Form(); // version 0
form.applyEvent({
id: ...,
aggregateId: ...,
type: 'FormCreated',
data: ...,
version: 1,
occurredAt: ...
});
Then form.version becomes 1.
That works.
- Now, let's design the Form aggregate with uncommittedEvents and methods.
class Form {
formId: string;
name: string;
description: string;
fields: Field[] = [];
isPublished: boolean = false;
version: number = 0;
uncommittedEvents: Event[] = [];
// We don't have a public constructor? We can have a static create method.
static create(formId: string, name: string, description: string): Form {
const form = new Form();
form.applyEvent({
id: uuid(),
aggregateId: formId,
type: 'FormCreated',
data: { formId, name, description },
version: 1,
occurredAt: new Date()
});
return form;
}
// Then other commands:
addField(command: AddFieldCommand) {
// business rules
if (this.isPublished) {
throw new Error('Cannot add field to a published form');
}
// check order uniqueness
if (this.fields.some(f => f.order === command.order)) {
throw new Error('Field order must be unique');
}
// check allowed rules for field type? We can have a method that returns allowed rules for a type? Let's assume we have a map:
const allowedRules = this.getAllowedRulesForFieldType(command.type);
for (const ruleConfig of command.validationRules) {
if (!allowedRules.includes(ruleConfig.type)) {
throw new Error(`Validation rule ${ruleConfig.type} is not allowed for field type ${command.type}`);
}
}
const field = new Field(
command.fieldId,
command.type,
command.label,
command.validationRules,
command.order
);
this.applyEvent({
id: uuid(),
aggregateId: this.formId,
type: 'FieldAdded',
data: {
fieldId: command.fieldId,
type: command.type,
label: command.label,
validationRules: command.validationRules,
order: command.order
},
version: this.version + 1,
occurredAt: new Date()
});
}
// ... similar for updateField and removeField.
applyEvent(event: Event) {
this.version = event.version;
switch (event.type) {
case 'FormCreated':
this.formId = event.data.formId;
this.name = event.data.name;
this.description = event.data.description;
break;
case 'FieldAdded':
const field = new Field(
event.data.fieldId,
event.data.type,
event.data.label,
event.data.validationRules,
event.data.order
);
this.fields.push(field);
this.fields.sort((a, b) => a.order - b.order);
break;
case 'FieldUpdated':
const index = this.fields.findIndex(f => f.id === event.data.fieldId);
if (index !== -1) {
this.fields[index] = new Field(
event.data.fieldId,
event.data.type,
event.data.label,
event.data.validationRules,
event.data.order
);
this.fields.sort((a, b) => a.order - b.order);
}
break;
case 'FieldRemoved':
this.fields = this.fields.filter(f => f.id !== event.data.fieldId);
break;
case 'FormPublished':
this.isPublished = true;
break;
}
}
// When we load from events, we don't want to push to uncommittedEvents. So we can have a method that applies an event without pushing:
private applyEventWithoutTracking(event: Event) {
this.applyEvent(event);
// but note: applyEvent sets the version and updates state. We don't want to push to uncommittedEvents? Actually, we are loading, so we don't have uncommittedEvents? We can have:
// We'll have a flag? Or we can have two methods: applyEvent (for new events) and replayEvent (for loading). But we already have applyEvent that sets version and updates state. We can use the same method for both, but then when loading we don't want to push to uncommittedEvents.
// Actually, when loading, we create a new Form and then call applyEvent for each event. The uncommittedEvents should be empty? We don't push in applyEvent? We only push when we are handling a command? Actually, we push the event to uncommittedEvents in the command method? No, we push in applyEvent? Let's change:
// In the command methods (addField, etc.), we create the event and then call applyEvent? But then applyEvent pushes to uncommittedEvents? We don't want that when replaying.
// So let's change:
// applyEvent(event: Event) {
// // update state
// // and push to uncommittedEvents? Only if we are not replaying? We can have a private flag? Or we can have:
// this.uncommittedEvents.push(event);
// this.version = event.version;
// ... update state
// }
// Then when replaying, we don't want to push. So we can have:
// applyEvent(event: Event, isReplay: boolean = false) {
// if (!isReplay) {
// this.uncommittedEvents.push(event);
// }
// this.version = event.version;
// ... update state
// }
// But then when we load, we call applyEvent(event, true). But then the command methods call applyEvent without the second argument (so false) and then push.
// Alternatively, we can have:
// private applyEventToState(event: Event) {
// this.version = event.version;
// ... update state
// }
// applyEvent(event: Event) {
// this.applyEventToState(event);
// this.uncommittedEvents.push(event);
// }
// replayEvent(event: Event) {
// this.applyEventToState(event);
// }
// Then in the command methods, we call applyEvent, and when replaying we call replayEvent.
// Let's do that.
}
getUncommittedEvents(): Event[] {
return this.uncommittedEvents;
}
clearUncommittedEvents() {
this.uncommittedEvents = [];
}
}
18. Now, the repository:
class FormRepository {
constructor(private eventStore: EventStore) {}
async getById(formId: string): Promise<Form> {
const events = await this.eventStore.getEventsForAggregate(formId);
const form = new Form();
for (const event of events) {
form.replayEvent(event);
}
return form;
}
async save(form: Form) {
const events = form.getUncommittedEvents();
await this.eventStore.storeEvents(events);
form.clearUncommittedEvents();
}
}
19. FormValidator:
class FormValidator {
validate(form: Form, values: { [fieldId: string]: string }): { [fieldId: string]: ValidationResult[] } {
const errors: { [fieldId: string]: ValidationResult[] } = {};
for (const field of form.fields) {
const value = values[field.id];
const result = field.validate(value);
if (!result.valid) {
if (!errors[field.id]) {
errors[field.id] = [];
}
errors[field.id].push(result);
}
}
return errors;
}
}
20. ValidationRule and Field:
interface ValidationRule {
validate(value: string): ValidationResult;
}
class RequiredRule implements ValidationRule {
constructor(private message?: string) {}
validate(value: string): ValidationResult {
if (value === undefined || value === null || value === '') {
return { valid: false, message: this.message ?? 'This field is required' };
}
return { valid: true };
}
}
class EmailRule implements ValidationRule {
constructor(private message?: string) {}
validate(value: string): ValidationResult {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (value && !emailRegex.test(value)) {
return { valid: false, message: this.message ?? 'Invalid email address' };
}
return { valid: true };
}
}
class MinLengthRule implements ValidationRule {
constructor(private min: number, private message?: string) {}
validate(value: string): ValidationResult {
if (value && value.length < this.min) {
return { valid: false, message: this.message ?? `Must be at least ${this.min} characters` };
}
return { valid: true };
}
}
// ... other rules.
class ValidationRuleFactory {
static create(config: any): ValidationRule {
switch (config.type) {
case 'required': return new RequiredRule(config.message);
case 'email': return new EmailRule(config.message);
case 'minLength': return new MinLengthRule(config.value, config.message);
// ... etc.
default: throw new Error(`Unknown validation rule type: ${config.type}`);
}
}
}
class Field {
constructor(
public id: string,
public type: string,
public label: string,
public validationRulesConfig: any[],
public order: number
) {}
validate(rawValue: string): ValidationResult {
for (const config of this.validationRulesConfig) {
const rule = ValidationRuleFactory.create(config);
const result = rule.validate(rawValue);
if (!result.valid) {
return result;
}
}
return { valid: true };
}
}
21. We might want to have a way to get the allowed rules for a field type? We can have a static map in the Form class? Or a separate service? Let's put it in the Form aggregate as a private method:
private getAllowedRulesForFieldType(fieldType: string): string[] {
const allowedRules: { [type: string]: string[] } = {
text: ['required', 'minLength', 'maxLength', 'pattern'],
email: ['required', 'email'],
number: ['required', 'min', 'max'],
// ... etc.
};
return allowedRules[fieldType] || [];
}
22. This is a basic design. We can extend it with more features.
-
Note: The event store implementation is not provided. We assume it can store and retrieve events by aggregateId in order.
-
We also need to handle concurrency? The version in the event can be used for optimistic concurrency? When saving, we can check that the version of the aggregate matches the last stored version? Actually, the event store should assign the version? We are assigning the version in the event as this.version+1. But if two commands happen at the same time, we might have a race condition? We can use the version for optimistic locking: when saving, we check that the last event's version is the same as the current aggregate's version? Actually, we are storing events in order. The event store should ensure that events for an aggregate are stored in order and we don't have two events with the same version? We are setting the version in the event as the next version (current version+1). So if two commands happen, they both will try to create an event with version=currentVersion+1? That's a problem.
We need to load the aggregate, then apply events, then save. If two transactions happen:
T1: load form (version=1)
T2: load form (version=1)
T1: add field -> event with version=2
T1: save (stores event with version=2)
T2: add field -> event with version=2 (because it still has version=1) -> then when saving, we try to store an event with version=2 but the last version is already 2? That's a conflict.
So we need to check the version when saving? We can have the event store check that the event's version is exactly the next version? Actually, the event store should store the event with the given version and then when loading, we get the events in order. But if two events have the same version, that's an error.
So we must ensure that the aggregate's version is incremented only when we apply an event and then we save. But if two aggregates are loaded and then both try to save, they both will try to save an event with the same version? We need to use optimistic concurrency: when saving, we check that the last event we have (the one we loaded) is still the last event in the store? We can do:
In the repository save:
const currentEvents = await eventStore.getEventsForAggregate(formId);
if (currentEvents.length > 0 && currentEvents[currentEvents.length-1].version !== form.version - 1) {
throw new ConcurrencyException();
}
But note: the form.version is the version of the last applied event. When we load, we set form.version to the last event's version. Then when we apply a new event, we set the new event's version to form.version+1 and then set form.version to that. So if we have two transactions, they both load with version=1, then both apply an event and set version=2. Then when saving, the first one saves and the store now has version=2. The second one tries to save an event with version=2 but the last version in the store is 2? Actually, the second one's event also has version=2? That's the same version? That's not allowed.
So we need to assign the version at the time of saving? Or we need to use a sequence number that is assigned by the event store? Usually, the event store assigns the version (or sequence) as the position in the stream. So we shouldn't set the version in the event? The event store will assign the version based on the current stream length.
Let's change: the aggregate does not set the version in the event. The event store will assign the version when storing? But then when we replay, we need the version to be in the event? We can have the event store assign a sequence number (which is the version) and store it. Then when we load, we get the events with their sequence numbers.
So the aggregate should not set the version. Instead, the event store will set the version (or sequence) when storing. Then when we load, we get the events with their versions.
Then the aggregate's version should be set to the version of the last event applied? But then when we apply an event, we don't know the version until it's stored? That's a problem because we need to set the version for the next event? Actually, we don't need to set the version in the event. The event store will assign it.
But then how do we handle concurrency? The event store can use the expected version: we load the current version (say 1) and then when saving, we expect the next version to be 2. The event store will check that the current version in the store is 1 and then assign 2 to the new event.
So the aggregate should not set the version. We remove the version from the event? But then when we replay, we don't have the version? Actually, the event store will assign a version (or sequence) to each event and store it. Then when we load, we get the events with their versions.
So the event object in the store might look like:
{
id: ...,
aggregateId: ...,
type: ...,
data: ...,
version: 1, // assigned by event store
occurredAt: ...
}
Then when we load, we get the version and set the aggregate's version to that event's version.
So in the aggregate, we don't set the version when creating the event. We just create the event without version? Then when we save, the event store will assign the version.
But then when we apply the event (during replay) we set the aggregate's version to the event's version. So we need the event to have a version.
So the event store must assign the version. We can have:
In the repository save:
const events = form.getUncommittedEvents();
const storedEvents = await this.eventStore.storeEvents(events, form.version); // we pass the expected current version? Actually, we pass the version that we think the aggregate is at? Then the event store will check that the current version in the store is that, and then assign the next version to each event? But we are storing multiple events? We might have multiple uncommitted events? Then we need to store them in one batch? The event store should store them in order and assign consecutive versions.
Alternatively, we store one event at a time? Then we can do:
for (const event of events) {
await this.eventStore.storeEvent(event, expectedVersion);
expectedVersion++;
}
But that's inefficient.
Alternatively, we can have the aggregate only have one uncommitted event at a time? Because we are handling one command at a time? Then we can store one event at a time.
But we might have a command that produces multiple events? Then we have multiple uncommitted events? We can store them in a batch? The event store must support batch storing and assign versions in order.
Given the complexity, let's assume we only have one event per command? Then we can store one event at a time.
But note: the FormCreated event is one event, and then each field added is one event. So we are safe.
Then:
In the repository save:
const event = form.getUncommittedEvents()[0]; // only one
await this.eventStore.storeEvent(event, form.version); // form.version is the current version (the last applied event's version). We expect the store to be at form.version, then store the event with version form.version+1.
Then after storing, we set form.version = event.version (which is assigned by the event store? Actually, the event store returns the stored event with the version assigned? Or we set the version in the aggregate after storing? We can have:
const storedEvent = await this.eventStore.storeEvent(event, form.version);
form.version = storedEvent.version;
form.clearUncommittedEvents();
But then the event store must return the stored event with the assigned version.
Alternatively, we can have the event store assign the version and then we update the aggregate's version to that? But note: the aggregate might have multiple uncommitted events? Then we need to set the version to the last event's version? We can do:
const storedEvents = await this.eventStore.storeEvents(events, form.version);
// storedEvents are the same events but with versions assigned? And in order?
form.version = storedEvents[storedEvents.length-1].version;
form.clearUncommittedEvents();
But again, we assume one event at a time.
Let's change the design: the aggregate should not set the version in the event. The event store will assign the version when storing. Then when we load, we get the events with their versions and set the aggregate's version to the last event's version.
So in the aggregate, when we create an event, we don't set the version. We just create the event without version? Then when we store, the event store will add the version.
But then when we replay, we need the version? The event store will store the version. So when we load, we get the event with the version.
So in the aggregate, we don't set the version in the event. We just set the other properties.
Then:
class Form {
// ...
addField(command: AddFieldCommand) {
// ... business rules
const event = {
id: uuid(),
aggregateId: this.formId,
type: 'FieldAdded',
data: {
fieldId: command.fieldId,
type: command.type,
label: command.label,
validationRules: command.validationRules,
order: command.order
},
occurredAt: new Date()
// no version
};
this.uncommittedEvents.push(event);
// We don't update the version here? Because we don't know the version until we store? But then when we apply the event (for the current state) we need to update the state? We are applying the event immediately? Actually, we are applying the event to the aggregate state in the command method? We are not? We are just pushing to uncommittedEvents? Then when we call applyEvent? We are not calling applyEvent in the command method? We are just creating the event and pushing? Then we need to apply the event to the state? Otherwise, the aggregate state is not updated until we replay? That's not good.
We need to apply the event to the current state immediately (so that the aggregate reflects the change) and also push to uncommittedEvents.
So we do:
this.applyEvent(event); // but applyEvent expects a version? We don't have the version yet.
We can change applyEvent to not require the version? Then we set the version after storing? But then the state is updated without the version? That's okay because the version is only for concurrency.
Actually, the version is part of the event, not the state. So we can update the state without the version? Then when we store, we get the version and then set the aggregate's version? But then the aggregate's version is not used for anything except for concurrency? We can store the version in the aggregate as the last applied event's version? But we don't have it until we store.
Alternatively, we can have the aggregate's version be the number of events applied (including the uncommitted ones)? Then when we apply an event (without storing) we increment the version? Then when we store, we use that version as the expected version? But then if we rollback? We don't rollback.
Let's do:
In the aggregate:
version: number = 0;
applyEvent(event: Event, withVersion?: boolean) {
if (withVersion) {
this.version = event.version;
}
// update state without version
}
Then in the command method:
const event = { ... without version ... };
this.applyEvent(event, false); // apply without setting version
this.uncommittedEvents.push(event);
Then when we store, the event store will assign the version and then we set the aggregate's version to the stored event's version.
But then when we replay, we call applyEvent(event, true) to set the version.
This is getting messy.
Given the complexity, let's go back: the aggregate should not be responsible for setting the version. The event store will assign the version. The aggregate's version should be set to the last stored event's version? Actually, the aggregate's version is the version of the last event that has been stored? But then when we have uncommitted events, we don't know the version? We can have:
In the aggregate:
version: number = 0; // the version of the last stored event? Actually, when we load, we set the version to the last event's version. Then when we apply a new event, we don't change the version? Then when we save, the event store will assign the next version? But then the aggregate's version is not updated until we save? That's okay because we only use the version for concurrency check when saving.
So:
In the repository save:
const events = form.getUncommittedEvents();
const lastStoredVersion = form.version;
const storedEvents = await this.eventStore.storeEvents(events, lastStoredVersion);
// storedEvents have versions assigned? And they are consecutive starting from lastStoredVersion+1?
form.version = storedEvents[storedEvents.length-1].version;
form.clearUncommittedEvents();
Then the aggregate's version is updated after saving.
And when we load, we set form.version to the last event's version.
So in the aggregate, we don't set the version in the event. We just create the event without version.
And we don't set the version when applying the event (during command handling or replay). We only set the version when we load (from the last event) and when we save (from the stored events).
But then when we apply an event (during command handling) we don't set the version? That's okay because the version is only for concurrency and we don't use it in the state.
However, we might have business rules that depend on the version? Unlikely.
So:
class Form {
formId: string;
name: string;
description: string;
fields: Field[] = [];
isPublished: boolean = false;
version: number = 0; // the version of the last stored event
uncommittedEvents: Event[] = [];
// When we load, we set the version to the last event's version.
// When we handle a command, we create an event (without version) and push to uncommittedEvents, and then apply the event to the state (without setting version).
// When we save, we store the uncommittedEvents and then update the version to the last stored event's version.
}
Then applyEvent only updates the state (fields, etc.) and does not touch the version.
And when replaying, we call applyEvent (which updates state) but we don't push to uncommittedEvents? We don't need to because we are loading.
But how do we set the version when loading? We can set it after we finish replaying? We can have:
const form = new Form();
for (const event of events) {
form.applyEvent(event); // state only
}
if (events.length > 0) {
form.version = events[events.length-1].version;
}
So the repository does that.
Let's adjust:
In Form:
applyEvent(event: Event) {
// update state only, no version change
switch (event.type) {
case 'FormCreated':
this.formId = event.data.formId;
this.name = event.data.name;
this.description = event.data.description;
break;
case 'FieldAdded':
const field = new Field(...);
this.fields.push(field);
this.fields.sort((a, b) => a.order - b.order);
break;
// ...
}
}
In the command methods:
addField(command: AddFieldCommand) {
// ... business rules
const event = {
id: uuid(),
aggregateId: this.formId,
type: 'FieldAdded',
data: { ... },
occurredAt: new Date()
};
this.applyEvent(event); // update state
this.uncommittedEvents.push(event);
}
In the repository:
async getById(formId: string): Promise<Form> {
const events = await this.eventStore.getEventsForAggregate(formId);
const form = new Form();
for (const event of events) {
form.applyEvent(event);
}
if (events.length > 0) {
form.version = events[events.length-1].version;
}
return form;
}
async save(form: Form) {
const events = form.getUncommittedEvents();
if (events.length === 0) {
return;
}
const storedEvents = await this.eventStore.storeEvents(events, form.version);
// storedEvents should have the same events but with versions assigned? And in order?
// We assume the event store returns the stored events with versions.
form.version = storedEvents[storedEvents.length-1].version;
form.clearUncommittedEvents();
}
Then the event store storeEvents method:
async storeEvents(events: Event[], expectedVersion: number): Promise<Event[]> {
// Check that the current version of the aggregate in the store is expectedVersion.
// Then store each event and assign version = expectedVersion + 1, expectedVersion + 2, etc.
// Then return the events with versions assigned.
}
25. This seems reasonable.
-
Let's code the Event interface:
interface Event {
id: string;
aggregateId: string;
type: string;
data: any;
occurredAt: Date;
version?: number; // only set by event store when storing? Actually, when we load, we get the version. When we create, we don't set it.
}
-
But note: when we load, the events have version. When we create, we don't set version. The event store will add the version when storing.
-
Now, the event store interface:
interface EventStore {
getEventsForAggregate(aggregateId: string): Promise<Event[]>;
storeEvents(events: Event[], expectedVersion: number): Promise<Event[]>; // returns the stored events with versions assigned.
}
-
We have to be cautious: the event store must store events in order and assign increasing versions for the same aggregate.
-
This design is now complete.
-
Let's write the code for the Form aggregate with the above changes.
-
We'll also add the business rule that a form cannot be modified after publishing? We can have:
In addField, updateField, removeField:
if (this.isPublished) {
throw new Error('Cannot modify a published form');
}
And in the publish command:
publish() {
if (this.isPublished) {
throw new Error('Form is already published');
}
this.applyEvent({
id: uuid(),
aggregateId: this.formId,
type: 'FormPublished',
data: {},
occurredAt: new Date()
});
}
And in applyEvent for FormPublished:
case 'FormPublished':
this.isPublished = true;
break;
-
We are done.
-
Note: This is a simplified design. In production, we might need to handle more complex scenarios (like transactions, snapshots, etc.) but this is a good starting point.
-
Let's write the code in a more structured way.
Due to the complexity and length, I'll write the key parts in pseudocode/TypeScript.
We'll define:
- Event (interface)
- Form (class)
- Field (class)
- ValidationRule (interface) and concrete rules
- ValidationRuleFactory (class)
- FormValidator (class)
- Commands (interfaces)
- EventStore (interface)
- FormRepository (class)
Let's code accordingly.
I'll design a dynamic form builder backend using Event Sourcing with Aggregates, Strategy Pattern for validation, and a CQRS-inspired approach. This design ensures auditability, flexibility, and complex business rule enforcement.
1. Core Domain Model (Aggregates)
Aggregate Root: Form
Encapsulates form lifecycle and invariants.
// form.aggregate.ts
export class Form {
private readonly id: FormId;
private name: string;
private description?: string;
private fields: Map<FieldId, FormField>;
private version: number;
private isPublished: boolean;
private uncommittedEvents: DomainEvent[] = [];
private constructor(
id: FormId,
name: string,
description?: string,
version = 0
) {
this.id = id;
this.name = name;
this.description = description;
this.version = version;
}
static create(id: FormId, name: string, description?: string): Form {
const form = new Form(id, name, description);
form.raiseEvent(new FormCreatedEvent(id, name, description));
return form;
}
addField(
fieldId: FieldId,
type: FieldType,
label: string,
validationStrategy: ValidationStrategy,
order: number
): void {
if (this.isPublished) {
throw new Error("Cannot modify published form");
}
const field = FormField.create(
fieldId,
this.id,
type,
label,
validationStrategy,
order
);
if (this.fields.has(fieldId)) {
throw new Error(`Field ${fieldId} already exists`);
}
this.fields.set(fieldId, field);
this.raiseEvent(
new FieldAddedEvent(this.id, fieldId, type, label, order, validationStrategy.toConfig())
);
}
updateField(
fieldId: FieldId,
updates: Partial<FormField>,
newValidationStrategy?: ValidationStrategy
): void {
const field = this.fields.get(fieldId);
if (!field) throw new Error(`Field ${fieldId} not found`);
const updatedField = field.update(updates, newValidationStrategy);
this.fields.set(fieldId, updatedField);
this.raiseEvent(
new FieldUpdatedEvent(
this.id,
fieldId,
updatedField.label,
updatedField.order,
newValidationStrategy?.toConfig() ?? field.validationStrategy.toConfig()
)
);
}
removeField(fieldId: FieldId): void {
if (!this.fields.has(fieldId)) {
throw new Error(`Field ${fieldId} not found`);
}
this.fields.delete(fieldId);
this.raiseEvent(new FieldRemovedEvent(this.id, fieldId));
}
publish(): void {
if (this.isPublished) return;
if (this.fields.size === 0) {
throw new Error("Cannot publish form with no fields");
}
this.isPublished = true;
this.raiseEvent(new FormPublishedEvent(this.id));
}
validate(values: Record<FieldId, any>): ValidationResult[] {
const results: ValidationResult[] = [];
for (const [fieldId, value] of Object.entries(values)) {
const field = this.fields.get(fieldId);
if (!field) continue; // Skip unknown fields
const result = field.validate(value);
if (!result.isValid) {
results.push({
fieldId,
message: result.message,
value: value
});
}
}
return results;
}
// Event sourcing methods
private raiseEvent(event: DomainEvent): void {
this.uncommittedEvents.push(event);
this.applyEvent(event);
}
applyEvent(event: DomainEvent): void {
this.version++;
switch (event.type) {
case "FormCreated":
this.id = event.formId;
this.name = event.name;
this.description = event.description;
break;
case "FieldAdded":
const field = FormField.fromEvent(event);
this.fields.set(event.fieldId, field);
break;
case "FieldUpdated":
const existing = this.fields.get(event.fieldId);
if (existing) {
const updated = existing.update(
{ label: event.label, order: event.order },
ValidationStrategy.fromConfig(event.validationConfig)
);
this.fields.set(event.fieldId, updated);
}
break;
case "FieldRemoved":
this.fields.delete(event.fieldId);
break;
case "FormPublished":
this.isPublished = true;
break;
}
}
getUncommittedEvents(): DomainEvent[] {
return this.uncommittedEvents;
}
clearUncommittedEvents(): void {
this.uncommittedEvents = [];
}
getSnapshot(): FormSnapshot {
return {
id: this.id,
name: this.name,
description: this.description,
fields: Array.from(this.fields.values()).map(f => f.toSnapshot()),
version: this.version,
isPublished: this.isPublished
};
}
}
Aggregate: FormField
Value object representing a single field.
// form-field.ts
export class FormField {
constructor(
public readonly id: FieldId,
public readonly formId: FormId,
public type: FieldType,
public label: string,
public validationStrategy: ValidationStrategy,
public order: number
) {}
static create(
id: FieldId,
formId: FormId,
type: FieldType,
label: string,
validationStrategy: ValidationStrategy,
order: number
): FormField {
return new FormField(id, formId, type, label, validationStrategy, order);
}
static fromEvent(event: FieldAddedEvent | FieldUpdatedEvent): FormField {
return new FormField(
event.fieldId,
event.formId,
event.type,
event.label,
ValidationStrategy.fromConfig(event.validationConfig),
event.order
);
}
update(
updates: Partial<Pick<FormField, 'label' | 'order'>>,
newValidationStrategy?: ValidationStrategy
): FormField {
return new FormField(
this.id,
this.formId,
this.type,
updates.label ?? this.label,
newValidationStrategy ?? this.validationStrategy,
updates.order ?? this.order
);
}
validate(value: any): ValidationResult {
return this.validationStrategy.validate(value, this.type);
}
toSnapshot(): FormFieldSnapshot {
return {
id: this.id,
type: this.type,
label: this.label,
validationConfig: this.validationStrategy.toConfig(),
order: this.order
};
}
}
2. Validation Strategy Pattern
Strategy Interface & Config
// validation.strategy.ts
export interface ValidationStrategy {
validate(value: any, fieldType: FieldType): ValidationResult;
toConfig(): ValidationConfig;
static fromConfig(config: ValidationConfig): ValidationStrategy;
}
export type ValidationConfig =
| { type: "required"; message?: string }
| { type: "email"; message?: string }
| { type: "minLength"; value: number; message?: string }
| { type: "maxLength"; value: number; message?: string }
| { type: "pattern"; regex: string; message?: string }
| { type: "custom"; validator: string; parameters?: Record<string, any> };
export interface ValidationResult {
isValid: boolean;
message?: string;
}
Concrete Strategies
// strategies/
export class RequiredStrategy implements ValidationStrategy {
constructor(private message?: string) {}
validate(value: any): ValidationResult {
if (value === undefined || value === null || value === "") {
return {
isValid: false,
message: this.message ?? "This field is required"
};
}
return { isValid: true };
}
toConfig(): ValidationConfig {
return { type: "required", message: this.message };
}
static fromConfig(config: ValidationConfig): ValidationStrategy {
if (config.type !== "required") {
throw new Error("Invalid config for RequiredStrategy");
}
return new RequiredStrategy(config.message);
}
}
export class EmailStrategy implements ValidationStrategy {
private static readonly EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
constructor(private message?: string) {}
validate(value: any): ValidationResult {
if (value && !EmailStrategy.EMAIL_REGEX.test(value)) {
return {
isValid: false,
message: this.message ?? "Invalid email format"
};
}
return { isValid: true };
}
toConfig(): ValidationConfig {
return { type: "email", message: this.message };
}
static fromConfig(config: ValidationConfig): ValidationStrategy {
if (config.type !== "email") {
throw new Error("Invalid config for EmailStrategy");
}
return new EmailStrategy(config.message);
}
}
// Factory for strategies
export class ValidationStrategyFactory {
private static strategies: Map<string, new (config: any) => ValidationStrategy> =
new Map([
["required", RequiredStrategy],
["email", EmailStrategy],
// Add more strategies...
]);
static create(config: ValidationConfig): ValidationStrategy {
const StrategyClass = this.strategies.get(config.type);
if (!StrategyClass) {
throw new Error(`Unknown validation strategy: ${config.type}`);
}
return new StrategyClass(config);
}
static fromConfig(config: ValidationConfig): ValidationStrategy {
return this.create(config);
}
static register(type: string, strategy: new (config: any) => ValidationStrategy) {
this.strategies.set(type, strategy);
}
}
3. Event Definitions
// events/
export abstract class DomainEvent {
abstract readonly type: string;
abstract readonly formId: FormId;
readonly occurredOn: Date;
readonly version: number;
constructor(
public readonly metadata: {
eventId: EventId;
correlationId?: string;
causationId?: string;
}
) {
this.occurredOn = new Date();
}
}
export class FormCreatedEvent extends DomainEvent {
readonly type = "FormCreated";
constructor(
public readonly formId: FormId,
public readonly name: string,
public readonly description?: string,
metadata?: EventMetadata
) {
super(metadata ?? { eventId: new EventId() });
}
}
export class FieldAddedEvent extends DomainEvent {
readonly type = "FieldAdded";
constructor(
public readonly formId: FormId,
public readonly fieldId: FieldId,
public readonly type: FieldType,
public readonly label: string,
public readonly order: number,
public readonly validationConfig: ValidationConfig,
metadata?: EventMetadata
) {
super(metadata ?? { eventId: new EventId() });
}
}
export class FieldUpdatedEvent extends DomainEvent {
readonly type = "FieldUpdated";
constructor(
public readonly formId: FormId,
public readonly fieldId: FieldId,
public readonly label: string,
public readonly order: number,
public readonly validationConfig: ValidationConfig,
metadata?: EventMetadata
) {
super(metadata ?? { eventId: new EventId() });
}
}
export class FieldRemovedEvent extends DomainEvent {
readonly type = "FieldRemoved";
constructor(
public readonly formId: FormId,
public readonly fieldId: FieldId,
metadata?: EventMetadata
) {
super(metadata ?? { eventId: new EventId() });
}
}
export class FormPublishedEvent extends DomainEvent {
readonly type = "FormPublished";
constructor(public readonly formId: FormId, metadata?: EventMetadata) {
super(metadata ?? { eventId: new EventId() });
}
}
4. Event Sourcing Infrastructure
Event Store Interface
// event-store.ts
export interface EventStore {
saveEvents(
aggregateId: string,
events: DomainEvent[],
expectedVersion: number
): Promise<void>;
getEventsForAggregate(aggregateId: string): Promise<DomainEvent[]>;
getSnapshot(aggregateId: string): Promise<FormSnapshot | null>;
saveSnapshot(aggregateId: string, snapshot: FormSnapshot): Promise<void>;
}
Repository Implementation
// form.repository.ts
export class FormRepository {
constructor(
private eventStore: EventStore,
private snapshotInterval = 10 // Snapshot every 10 events
) {}
async get(formId: FormId): Promise<Form> {
const snapshot = await this.eventStore.getSnapshot(formId);
const events = await this.eventStore.getEventsForAggregate(formId);
let form: Form;
let lastEventVersion = 0;
if (snapshot) {
form = Form.fromSnapshot(snapshot);
lastEventVersion = snapshot.version;
// Replay events after snapshot
const eventsAfterSnapshot = events.filter(e => e.version > lastEventVersion);
for (const event of eventsAfterSnapshot) {
form.applyEvent(event);
}
} else {
form = new Form(formId, ""); // Empty form, will be populated by events
for (const event of events) {
form.applyEvent(event);
}
}
return form;
}
async save(form: Form): Promise<void> {
const events = form.getUncommittedEvents();
if (events.length === 0) return;
const expectedVersion = form.version - events.length;
await this.eventStore.saveEvents(form.id, events, expectedVersion);
// Save snapshot if threshold reached
if (events.length >= this.snapshotInterval) {
await this.eventStore.saveSnapshot(form.id, form.getSnapshot());
}
form.clearUncommittedEvents();
}
}
5. Application Services (CQRS Commands/Queries)
// application/
export class FormCommandService {
constructor(private formRepository: FormRepository) {}
async createForm(command: CreateFormCommand): Promise<FormId> {
const formId = new FormId();
const form = Form.create(formId, command.name, command.description);
await this.formRepository.save(form);
return formId;
}
async addField(command: AddFieldCommand): Promise<void> {
const form = await this.formRepository.get(command.formId);
const strategy = ValidationStrategyFactory.create(command.validationConfig);
form.addField(
new FieldId(),
command.type,
command.label,
strategy,
command.order
);
await this.formRepository.save(form);
}
async submitForm(formId: FormId, values: Record<FieldId, any>): Promise<FormSubmissionResult> {
const form = await this.formRepository.get(formId);
if (!form.isPublished) {
throw new Error("Form is not published");
}
const validationErrors = form.validate(values);
if (validationErrors.length > 0) {
return {
success: false,
errors: validationErrors
};
}
// In real implementation, you'd also store the submission
return {
success: true,
errors: [],
submittedAt: new Date()
};
}
}
export class FormQueryService {
constructor(private eventStore: EventStore) {}
async getFormDefinition(formId: FormId): Promise<FormDefinitionDto> {
const form = await this.formRepository.get(formId);
return {
id: form.id,
name: form.name,
description: form.description,
fields: Array.from(form.fields.values()).map(f => ({
id: f.id,
type: f.type,
label: f.label,
validation: f.validationStrategy.toConfig(),
order: f.order
})),
isPublished: form.isPublished
};
}
}
6. DTOs & Types
// dto.ts
export interface FormDefinitionDto {
id: string;
name: string;
description?: string;
fields: Array<{
id: string;
type: string;
label: string;
validation: ValidationConfig;
order: number;
}>;
isPublished: boolean;
}
export interface FormSubmissionResult {
success: boolean;
errors: Array<{ fieldId: string; message: string; value: any }>;
submittedAt?: Date;
}
// Value Objects
export class FormId {
constructor(public readonly value: string) {}
toString(): string {
return this.value;
}
static generate(): FormId {
return new FormId(crypto.randomUUID());
}
}
export class FieldId {
constructor(public readonly value: string) {}
static generate(): FieldId {
return new FieldId(crypto.randomUUID());
}
}
export type FieldType =
| "text"
| "email"
| "number"
| "textarea"
| "select"
| "checkbox"
| "radio";
7. Example Usage
// Example workflow
const commandService = new FormCommandService(formRepository);
// 1. Create form
const formId = await commandService.createForm({
name: "Contact Form",
description: "Customer contact form"
});
// 2. Add fields with different validation strategies
await commandService.addField({
formId,
type: "text",
label: "Full Name",
validationConfig: { type: "required", message: "Name is required" },
order: 1
});
await commandService.addField({
formId,
type: "email",
label: "Email",
validationConfig: { type: "email" },
order: 2
});
await commandService.addField({
formId,
type: "text",
label: "Message",
validationConfig: {
type: "minLength",
value: 10,
message: "Message must be at least 10 characters"
},
order: 3
});
// 3. Publish form
// (Would need a publish command - omitted for brevity)
// 4. Validate submission
const result = await commandService.submitForm(formId, {
field1: "John Doe",
field2: "john@example.com",
field3: "Hello world"
});
Key Design Decisions & Benefits
-
Event Sourcing Benefits:
- Full audit trail of all form changes
- Temporal queries (e.g., "show form as of last Tuesday")
- Easy debugging (replay events to reconstruct state)
-
Strategy Pattern for Validation:
- Pluggable validation rules
- Easy to add custom validators
- Validation logic decoupled from form structure
-
Aggregate Design:
Form maintains invariants (e.g., can't modify published forms)
- All changes go through aggregate methods
- Business rules encapsulated in aggregate
-
Snapshotting:
- Optimizes performance for forms with many events
- Configurable snapshot interval
-
CQRS Separation:
- Commands change state (mutate aggregate)
- Queries read optimized DTOs
- Clear separation of concerns
-
Extensibility:
- New field types: extend
FieldType union
- New validation strategies: implement
ValidationStrategy
- Custom business rules: add methods to
Form aggregate
Potential Enhancements
- Schema Versioning: Add version field to event configs for backward compatibility
- Conditional Validation: Add
dependsOn field in validation config for cross-field validation
- Dynamic Options: For select fields, store options as separate
FieldOption aggregate
- Permissions: Add
AccessControlList aggregate for form sharing
- Analytics: Project events to read models for form usage statistics
- Webhooks:
FormPublishedEvent could trigger external notifications
This design provides a robust, scalable foundation for a dynamic form builder with full event history, flexible validation, and clear domain boundaries.