-
-
Notifications
You must be signed in to change notification settings - Fork 268
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
KhraksMamtsov
wants to merge
7
commits into
Effect-TS:next-minor
Choose a base branch
from
KhraksMamtsov:schema-form-data
base: next-minor
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+409
−0
Open
Changes from 2 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
60a8222
add FormData and FormDataFromSelf
KhraksMamtsov 63c60b5
switched from arrays to sets
KhraksMamtsov e60e3ff
fix changeset description
KhraksMamtsov a6f5152
renaming
KhraksMamtsov bc26407
handle Files as well
KhraksMamtsov 02626ee
add tests with FileFromSelf schema
KhraksMamtsov edc9cdf
use Blob instead of File
KhraksMamtsov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"effect": minor | ||
--- | ||
|
||
`FormData` and `FormDataFromSelf` have benn added | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
*/ | ||
|
59 changes: 59 additions & 0 deletions
59
packages/effect/test/Schema/Schema/FormData/FormData.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
114
packages/effect/test/Schema/Schema/FormData/FormDataFromSelf.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] })`) | ||
}) | ||
}) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
been