From 73c74c503a9b7c0a600ed5c64f6c56613a67dd5d Mon Sep 17 00:00:00 2001 From: Danielo Rodriguez Date: Tue, 24 Oct 2023 11:58:27 +0200 Subject: [PATCH] wip: migration functions --- src/core/formDefinition.ts | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/core/formDefinition.ts b/src/core/formDefinition.ts index 297ad017..da5fa795 100644 --- a/src/core/formDefinition.ts +++ b/src/core/formDefinition.ts @@ -1,4 +1,4 @@ -import { object, number, literal, type Output, is, array, string, union, optional, safeParse, minLength, toTrimmed, merge, any } from "valibot"; +import { object, number, literal, type Output, is, array, string, union, optional, safeParse, minLength, toTrimmed, merge, any, SafeParseResult, Issues } from "valibot"; /** * Here are the core logic around the main domain of the plugin, * which is the form definition. @@ -81,6 +81,35 @@ const FormDefinitionV1Schema = merge([FormDefinitionBasicSchema, object({ version: literal("1"), fields: FieldListSchema, })]); + +type FormDefinitionV1 = Output; +class MigrationError { + constructor(readonly issues: Issues) { } +} + +function fromV0toV1(data: unknown): FormDefinitionV1 | MigrationError { + const v0 = safeParse(FormDefinitionBasicSchema, data) + if (!v0.success) { + return new MigrationError(v0.issues) + } + const unparsedV1 = { + ...v0.output, + version: "1", + } + const v1 = safeParse(FormDefinitionV1Schema, unparsedV1) + if (!v1.success) { + return new MigrationError(v1.issues) + } + return v1.output +} + +export function migrateToLatest(data: unknown): FormDefinition | MigrationError { + if (is(FormDefinitionV1Schema, data)) { + return data; + } + return fromV0toV1(data); +} + //=========== Types derived from schemas type selectFromNotes = Output; type inputSlider = Output;