sveltekit-superforms icon indicating copy to clipboard operation
sveltekit-superforms copied to clipboard

Provide reducers/reviviers for devalue in superForm/superValidate functions

Open ktarmyshov opened this issue 1 year ago • 2 comments

Is your feature request related to a problem? Please describe. I'm using Decimal.js in zod schemas. When I use the superForm with dataType='json', posting data fails during devalue.stringify, because it cannot serialize custom type "Decimal".

Describe the solution you'd like Feature request: provide possibility to pass reducers/revivers to superForm/superValidate to parse the request data accordingly.

Describe alternatives you've considered

    async onSubmit(input) {
      // Reduce custom types before submitting
      const formData = await superFormResult.validateForm();
      if (formData.valid) {
        const formJsonData = JSON.parse(JSON.stringify(formData.data));
        input.jsonData(formJsonData);
      }
    },

I also tried to fork and npm-link the devalue package for sveltekit (to provide default reducers/revivers for sveltekit), but superforms is using 4.3.3 and sveltekit 5.0.0 (which may still be different in the future). Even if I "override" the dependency to use 5.0.0, this one instantiated in a different (memory) context and default reducers/revivers working for sveltekit are empty for superforms - so "no go".

Additional context None

ktarmyshov avatar May 06 '24 10:05 ktarmyshov

This would be really interesting and it's something we wan't aswell. We use the MongoDB ObjectId class.

There is a discussion about this in svelte kit aswell https://github.com/sveltejs/kit/issues/9401 maybe if implemented there it would solve these issues aswell?

AndreasHald avatar May 08 '24 06:05 AndreasHald

I tried creating a PR for this, by creating an object like this

export class Vector {
    x: number;
    y: number;
	constructor(x: number, y: number) {
		this.x = x;
		this.y = y;
	}
	magnitude() {
		return Math.sqrt(this.x * this.x + this.y * this.y);
	}
}


export const complexTypes: CustomTypeOptions = {
    reducers: {
        Vector: (value) => value instanceof Vector && [value.x, value.y]
    },
    revivers: {
        Vector: ([x,y]) => new Vector(x,y)
    },
    defaults: {
        Vector: () => new Vector(0,0)
    }
}

and providing it to SuperForms, a lot of stuff ends up working. But it breaks when you return data from a load function to the form, in the end at least as far as I can see, this needs to happen at a svelte kit level.

AndreasHald avatar Jul 03 '24 08:07 AndreasHald

It seems like https://github.com/sveltejs/kit/issues/9401 doesn't make any progress, so maybe this can be an addition for v3. Need to think about a good interface for it though, as the basic return { form } won't work directly.

ciscoheat avatar Oct 08 '24 10:10 ciscoheat