Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FormData and FormDataFromSelf #4011

Open
wants to merge 7 commits into
base: next-minor
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/rare-ducks-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

`FormData` and `FormDataFromSelf` have benn added
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

been

192 changes: 192 additions & 0 deletions packages/effect/src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4466,6 +4466,198 @@ export const split = (separator: string): transform<typeof String$, Array$<typeo
{ strict: true, decode: string_.split(separator), encode: array_.join(separator) }
)

function getFieldsTypes(ast: AST.AST, result: {
arrays: Set<string>
strings: Set<string>
}, propName?: string): {
arrays: Set<string>
strings: Set<string>
} {
switch (ast._tag) {
case "Suspend": {
return getFieldsTypes(ast.f(), result, propName)
}
case "Refinement": {
return getFieldsTypes(ast.from, result, propName)
}
case "Union": {
return ast.types.reduce((acc, cur) => getFieldsTypes(cur, acc, propName), result)
}
case "Transformation": {
return getFieldsTypes(ast.from, result, propName)
}
case "TypeLiteral": {
ast.propertySignatures.forEach((ps) => {
const psName = ps.name
if (typeof psName === "string") {
getFieldsTypes(ps.type, result, psName)
}
})
return result
}
case "TupleType": {
if (propName !== undefined) {
result.arrays.add(propName)
}
return result
}
default: {
if (propName !== undefined) {
result.strings.add(propName)
}
return result
}
}
}

function compileFormDataToObject(ast: AST.AST) {
const fieldsTypes = getFieldsTypes(ast, { arrays: new Set(), strings: new Set() })

return (fd: FormData): Record<string, string | ReadonlyArray<string>> => {
const obj: Record<string, any> = {}
fieldsTypes.arrays.forEach((arrayFieldKey) => (obj[arrayFieldKey] = []))

fd.forEach((value, key) => {
if (typeof value !== "string") return
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should also handle File / Blob instances.


if (fieldsTypes.strings.has(key)) {
obj[key] = value
} else if (fieldsTypes.arrays.has(key)) {
obj[key].push(value)
} else {
return
}
})

return obj
}
}

function objectToFormData(obj: Record<string, string | ReadonlyArray<string>>): FormData {
const fd = new FormData()
Object.entries(obj).forEach((member) => {
const [key, value] = member
if (Array.isArray(value)) {
value.forEach((v: string) => fd.append(key, v))
} else {
fd.append(key, value as string)
}
})
return fd
}

const formDataParse = (options: {
formDataToObject: (fd: FormData) => Record<string, string | ReadonlyArray<string>>
objectToFormData: (obj: Record<string, string | ReadonlyArray<string>>) => FormData
}) =>
<A extends Record<string, string | ReadonlyArray<string>>, R>(
decodeUnknown: ParseResult.DecodeUnknown<A, R>
): ParseResult.DeclarationDecodeUnknown<FormData, R> =>
(u, _options, ast) =>
(u instanceof FormData) ?
toComposite(decodeUnknown(options.formDataToObject(u), _options), options.objectToFormData, ast, u)
: ParseResult.fail(new ParseResult.Type(ast, u))

const formDataArbitrary =
(objectToFormData: (obj: Record<string, string | ReadonlyArray<string>>) => FormData) =>
<A extends Record<string, string | ReadonlyArray<string>>>(
value: LazyArbitrary<A>
): LazyArbitrary<FormData> =>
(fc) => value(fc).map(objectToFormData)

const formDataEquivalence =
(formDataToObject: (fd: FormData) => Record<string, string | ReadonlyArray<string>>) =>
<A extends Record<string, string | ReadonlyArray<string>>>(
isEquivalent: Equivalence.Equivalence<A>
) => Equivalence.make<FormData>((a, b) => isEquivalent(formDataToObject(a) as A, formDataToObject(b) as A))

/**
* @category api interface
* @since 3.11.0
*/
export interface FormDataFromSelf<Value extends Schema.Any> extends
AnnotableClass<
FormDataFromSelf<Value>,
FormData,
FormData,
Schema.Context<Value>
>
{}

/**
* @category FormData constructors
* @since 3.11.0
*/
export const FormDataFromSelf = <
A extends Record<string, string | ReadonlyArray<string>>,
I extends Record<string, string | ReadonlyArray<string>>,
R
>(
value: Schema<A, I, R>
): FormDataFromSelf<Schema<A, I, R>> => {
const formDataToObject = compileFormDataToObject(value.ast)

const formDataParse_ = formDataParse({
formDataToObject,
objectToFormData
})

return declare(
[value],
{
decode: (value) => formDataParse_(ParseResult.decodeUnknown(value)),
encode: (value) => formDataParse_(ParseResult.encodeUnknown(value))
},
{
description: `FormData<${format(value)}>`,
pretty: (pretty) => (fd) => `FormData(${pretty(formDataToObject(fd) as A)})`,
arbitrary: formDataArbitrary(objectToFormData),
equivalence: formDataEquivalence(formDataToObject)
}
)
}

/**
* @category api interface
* @since 3.11.0
*/
export interface FormData$<Value extends Schema.Any> extends
AnnotableClass<
FormData$<Value>,
Schema.Type<Value>,
FormData,
Schema.Context<Value>
>
{}

/** @ignore */
const FormData$ = <
A,
I extends Record<string, string | ReadonlyArray<string>>,
R
>(
value: Schema<A, I, R>
) => {
const formDataToObject = compileFormDataToObject(value.ast)
return transform(
FormDataFromSelf(encodedSchema(value)),
value,
{
strict: true,
decode: (fd) => formDataToObject(fd) as I,
encode: objectToFormData
}
)
}

export {
/**
* @category FormData constructors
* @since 3.11.0
*/
FormData$ as FormData
}

/**
* @since 3.10.0
*/
Expand Down
59 changes: 59 additions & 0 deletions packages/effect/test/Schema/Schema/FormData/FormData.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import * as Pretty from "effect/Pretty"
import * as S from "effect/Schema"
import * as Util from "effect/test/Schema/TestUtils"
import { describe, expect, it } from "vitest"

describe("FormData", () => {
const schema = S.FormData(S.Struct({
prop1: S.NumberFromString
}))

it("property tests", () => {
Util.roundtrip(schema)
})

it("arbitrary", () => {
Util.expectArbitrary(S.FormData(S.Struct({
prop1: S.NumberFromString
})))
})

it("decoding", async () => {
const fd = new FormData()
fd.append("prop1", "1")
await Util.expectDecodeUnknownSuccess(
schema,
fd,
{ prop1: 1 }
)

const wrongFd = new FormData()
wrongFd.append("prop1", "false")
await Util.expectDecodeUnknownFailure(
schema,
wrongFd,
`(FormData<{ readonly prop1: string }> <-> { readonly prop1: NumberFromString })
└─ Type side transformation failure
└─ { readonly prop1: NumberFromString }
└─ ["prop1"]
└─ NumberFromString
└─ Transformation process failure
└─ Expected NumberFromString, actual "false"`
)
})

it("encoding", async () => {
const fd = new FormData()
fd.append("prop1", "2")
await Util.expectEncodeSuccess(
schema,
{ prop1: 2 },
fd
)
})

it("Pretty", () => {
const pretty = Pretty.make(schema)
expect(pretty({ prop1: 108 })).toEqual("{ \"prop1\": 108 }")
})
})
114 changes: 114 additions & 0 deletions packages/effect/test/Schema/Schema/FormData/FormDataFromSelf.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import * as Pretty from "effect/Pretty"
import * as S from "effect/Schema"
import * as Util from "effect/test/Schema/TestUtils"
import { describe, expect, it } from "vitest"

function objectToFormData(obj: Record<string, string | ReadonlyArray<string>>): FormData {
const fd = new FormData()
Object.entries(obj).forEach((member) => {
const [key, value] = member
if (Array.isArray(value)) {
value.forEach((v: string) => fd.append(key, v))
} else {
value
fd.append(key, value as string)
}
})
return fd
}

describe("FormDataFromSelf", () => {
const _schema = S.Struct({
str: S.String,
arr: S.Array(S.String)
})
const schema = S.FormDataFromSelf(_schema)

it("property tests", () => {
Util.roundtrip(schema)
})

it("equivalence", () => {
const isEquivalent = S.equivalence(schema)

expect(isEquivalent(
objectToFormData({ str: "str" }),
objectToFormData({ str: "str" })
)).toBe(true)
expect(isEquivalent(
objectToFormData({ str: "str" }),
objectToFormData({ str: "x" })
)).toBe(false)
expect(isEquivalent(
objectToFormData({ str: "str", arr: [] }),
objectToFormData({ str: "str" })
)).toBe(true)
expect(isEquivalent(
objectToFormData({ str: "str", arr: ["2"] }),
objectToFormData({ str: "str" })
)).toBe(false)
})

it("arbitrary", () => {
Util.expectArbitrary(
S.FormDataFromSelf(S.Struct({
str: S.String,
arr: S.Array(S.String)
}))
)
})

it("decoding", async () => {
await Util.expectDecodeUnknownSuccess(
schema,
objectToFormData({ str: "prop1" }),
objectToFormData({ str: "prop1" })
)
await Util.expectDecodeUnknownSuccess(
schema,
objectToFormData({ str: "prop1" }),
objectToFormData({ str: "prop1", arr: [] })
)
await Util.expectDecodeUnknownFailure(
schema,
objectToFormData({}),
`FormData<{ readonly str: string; readonly arr: ReadonlyArray<string> }>
└─ { readonly str: string; readonly arr: ReadonlyArray<string> }
└─ ["str"]
└─ is missing`
)
})

it("encoding", async () => {
await Util.expectEncodeSuccess(
schema,
objectToFormData({
str: "str"
}),
objectToFormData({
str: "str"
})
)
await Util.expectEncodeSuccess(
schema,
objectToFormData({
str: "str",
arr: []
}),
objectToFormData({
str: "str"
})
)
})

it("Pretty", () => {
const pretty = Pretty.make(schema)
const fd = objectToFormData({
str: "str",
arr: ["arr1", "arr2"],
prop1: ["el1", "el2"],
prop2: "prop2"
})
expect(pretty(fd)).toEqual(`FormData({ "str": "str", "arr": ["arr1", "arr2"] })`)
})
})