refactor: extract toWizardErrors, adopted by all 3 wizards (RD-20)
Each wizard flattened its per-field error record into the shell's WizardError[] summary with its own copy of the same loop. Extract one pure helper, wizard-errors.ts, next to naarStapLabel. Add a spec that covers a flat record, an empty record, skipped undefined/empty-string values, the idPrefix, and a skipped nested object. registratie-wizard.machine.ts changes Errors from an interface to a type alias, because only a type alias gets an implicit index signature and is assignable to the helper's Record<string, unknown> parameter. The other two machines already declare their error maps as type aliases, so this also makes the three consistent. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { toWizardErrors } from './wizard-errors';
|
||||
|
||||
describe('toWizardErrors', () => {
|
||||
it('flattens a flat record of field errors', () => {
|
||||
expect(toWizardErrors({ straat: 'Verplicht', postcode: 'Ongeldig' })).toEqual([
|
||||
{ id: 'straat', message: 'Verplicht' },
|
||||
{ id: 'postcode', message: 'Ongeldig' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns an empty list for an empty record', () => {
|
||||
expect(toWizardErrors({})).toEqual([]);
|
||||
});
|
||||
|
||||
it('skips a value that is undefined', () => {
|
||||
expect(toWizardErrors({ straat: undefined })).toEqual([]);
|
||||
});
|
||||
|
||||
it('skips a value that is an empty string', () => {
|
||||
expect(toWizardErrors({ straat: '' })).toEqual([]);
|
||||
});
|
||||
|
||||
it('prefixes every id with idPrefix when given', () => {
|
||||
expect(toWizardErrors({ q1: 'Verplicht' }, 'vraag-')).toEqual([
|
||||
{ id: 'vraag-q1', message: 'Verplicht' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('skips a value that is a nested object, so the caller can flatten it separately', () => {
|
||||
expect(toWizardErrors({ straat: 'Verplicht', antwoorden: { q1: 'Verplicht' } })).toEqual([
|
||||
{ id: 'straat', message: 'Verplicht' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { WizardError } from './wizard-shell.component';
|
||||
|
||||
/** Flatten a machine's per-field error record into the shell's summary list.
|
||||
Values that are not a non-empty string are skipped, so a nested group
|
||||
(the registratie wizard's `antwoorden`) is appended by the caller with its
|
||||
own `idPrefix` rather than special-cased here. */
|
||||
export function toWizardErrors(errors: Record<string, unknown>, idPrefix = ''): WizardError[] {
|
||||
const out: WizardError[] = [];
|
||||
for (const [k, v] of Object.entries(errors)) {
|
||||
if (typeof v === 'string' && v) out.push({ id: idPrefix + k, message: v });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Reference in New Issue
Block a user