Effect CommunityEC
Effect Community•2y ago•
5 replies
phischer

Building a Type-Safe FormData Helper in TypeScript

Did someone already try to build a FormData helper?

I would like to define a schema like this:

const RenamePersonFormSchema = Form({
        name: Schema.String,
    })

const formData = new FormData()
formData.append("name", "Jack")

Schema.decodeSync(RenamePersonFormSchema)(formData)


I tried with something like this, but I get type errors:

const Form = <A extends Schema.Struct.Fields>(
    structSchema: A,
) =>
    Schema.transformOrFail(
        Schema.instanceOf(FormData),
        Schema.Struct(structSchema),
        {
            strict: true,
            decode: (input, options, ast) => {
                const objectFromForm = Object.fromEntries(input)
                const result = Schema.decodeUnknownEither(Schema.Struct(structSchema))(
                    objectFromForm,
                )
                if (Either.isLeft(result)) {
                    return ParseResult.fail(new ParseResult.Type(ast, input, "FormData does not match defined fields"))
                }
                return ParseResult.succeed(result.right)
            },
            encode: (item) => {
                const formData = new FormData()

                for (var key in item) {
                    formData.append(key, item[key])
                }

                return ParseResult.succeed(formData)
            },        
    },
    )


I'm not sure if transformOrFail is even the right direction.

Playground is here: https://effect.website/play#9d3bd6a9d4b1

Any help would be appreciated 😊
Was this page helpful?