Skip to content

Schema 0.68 (Release)

The ParseIssue model in the @effect/schema/ParseResult module has undergone a comprehensive redesign and simplification that enhances its expressiveness without compromising functionality. This section explores the motivation and details of this refactoring.

The Schema.filter API has been improved to support more complex filtering that can involve multiple properties of a struct. This is especially useful for validations that compare two fields, such as ensuring that a password field matches a confirm_password field, a common requirement in form validations.

Previous Limitations:

Previously, while it was possible to implement a filter that compared two fields, there was no straightforward way to attach validation messages to a specific field. This posed challenges, especially in form validations where precise error reporting is crucial.

Example of Previous Implementation:

1
import { ArrayFormatter, Schema } from "@effect/schema"
2
import { Either } from "effect"
3
4
const Password = Schema.Trim.pipe(Schema.minLength(1))
5
6
const MyForm = Schema.Struct({
7
password: Password,
8
confirm_password: Password
9
}).pipe(
10
Schema.filter((input) => {
11
if (input.password !== input.confirm_password) {
12
return "Passwords do not match"
13
}
14
})
15
)
16
17
console.log(
18
"%o",
19
Schema.decodeUnknownEither(MyForm)({
20
password: "abc",
21
confirm_password: "d"
22
}).pipe(
23
Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error))
24
)
25
)
26
/*
27
{
28
_id: 'Either',
29
_tag: 'Left',
30
left: [
31
{
32
_tag: 'Type',
33
path: [],
34
message: 'Passwords do not match'
35
}
36
]
37
}
38
*/

In this scenario, while the filter functionally works, the lack of a specific error path (path: []) means errors are not as descriptive or helpful as they could be.

With the new improvements, it’s now possible to specify an error path along with the message, which enhances error specificity and is particularly beneficial for integration with tools like react-hook-form.

Updated Implementation Example:

1
import { ArrayFormatter, Schema } from "@effect/schema"
2
import { Either } from "effect"
3
4
const Password = Schema.Trim.pipe(Schema.minLength(1))
5
6
const MyForm = Schema.Struct({
7
password: Password,
8
confirm_password: Password
9
}).pipe(
10
Schema.filter((input) => {
11
if (input.password !== input.confirm_password) {
12
return {
13
path: ["confirm_password"],
14
message: "Passwords do not match"
15
}
16
}
17
})
18
)
19
20
console.log(
21
"%o",
22
Schema.decodeUnknownEither(MyForm)({
23
password: "abc",
24
confirm_password: "d"
25
}).pipe(
26
Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error))
27
)
28
)
29
/*
30
{
31
_id: 'Either',
32
_tag: 'Left',
33
left: [
34
{
35
_tag: 'Type',
36
path: [ 'confirm_password' ],
37
message: 'Passwords do not match'
38
}
39
]
40
}
41
*/

This modification allows the error to be directly associated with the confirm_password field, improving clarity for the end-user.

The refactored API also supports reporting multiple issues at once, which is useful in forms where several validation checks might fail simultaneously.

Example of Multiple Issues Reporting:

1
import { ArrayFormatter, Schema } from "@effect/schema"
2
import { Either } from "effect"
3
4
const Password = Schema.Trim.pipe(Schema.minLength(1))
5
const OptionalString = Schema.optional(Schema.String)
6
7
const MyForm = Schema.Struct({
8
password: Password,
9
confirm_password: Password,
10
name: OptionalString,
11
surname: OptionalString
12
}).pipe(
13
Schema.filter((input) => {
14
const issues: Array<Schema.FilterIssue> = []
15
// passwords must match
16
if (input.password !== input.confirm_password) {
17
issues.push({
18
path: ["confirm_password"],
19
message: "Passwords do not match"
20
})
21
}
22
// either name or surname must be present
23
if (!input.name && !input.surname) {
24
issues.push({
25
path: ["surname"],
26
message: "Surname must be present if name is not present"
27
})
28
}
29
return issues
30
})
31
)
32
33
console.log(
34
"%o",
35
Schema.decodeUnknownEither(MyForm)({
36
password: "abc",
37
confirm_password: "d"
38
}).pipe(
39
Either.mapLeft((error) => ArrayFormatter.formatErrorSync(error))
40
)
41
)
42
/*
43
{
44
_id: 'Either',
45
_tag: 'Left',
46
left: [
47
{
48
_tag: 'Type',
49
path: [ 'confirm_password' ],
50
message: 'Passwords do not match'
51
},
52
{
53
_tag: 'Type',
54
path: [ 'surname' ],
55
message: 'Surname must be present if name is not present'
56
}
57
]
58
}
59
*/

The ParseIssue type has undergone a significant restructuring to improve its expressiveness and simplicity. This new model categorizes issues into leaf and composite types, enhancing clarity and making error handling more systematic.

Structure of ParseIssue Type:

1
export type ParseIssue =
2
// leaf
3
| Type
4
| Missing
5
| Unexpected
6
| Forbidden
7
// composite
8
| Pointer
9
| Refinement
10
| Transformation
11
| Composite

Key Changes in the Model:

  1. New Members:

    • Composite: A new class that aggregates multiple ParseIssue instances.
    • Missing: Identifies when a required element or value is absent.
    • Unexpected: Flags unexpected elements or values in the input.
    • Pointer: Points to the part of the data structure where an issue occurs.
  2. Removed Members:

    • Previous categories like Declaration, TupleType, TypeLiteral, Union, Member, Key, and Index have been consolidated under the Composite type for a more streamlined approach.

Definition of Composite:

1
interface Composite {
2
readonly _tag: "Composite"
3
readonly ast: AST.Annotated
4
readonly actual: unknown
5
readonly issues: ParseIssue | NonEmptyReadonlyArray<ParseIssue>
6
readonly output?: unknown
7
}

We’ve updated our internal function getErrorMessage to enhance how error messages are formatted throughout our application. This function constructs an error message that includes the reason for the error, additional details, the path to where the error occurred, and the schema’s AST representation if available.

Example

1
import { JSONSchema, Schema } from "@effect/schema"
2
3
JSONSchema.make(Schema.Struct({ a: Schema.Void }))
4
/*
5
throws:
6
Error: Missing annotation
7
at path: ["a"]
8
details: Generating a JSON Schema for this schema requires a "jsonSchema" annotation
9
schema (VoidKeyword): void
10
*/

Annotations are used to add metadata to tuple elements, which can describe the purpose or requirements of each element more clearly. This can be particularly useful when generating documentation or JSON schemas from your schemas.

1
import { JSONSchema, Schema } from "@effect/schema"
2
3
// Defining a tuple with annotations for each coordinate in a point
4
const Point = Schema.Tuple(
5
Schema.element(Schema.Number).annotations({
6
title: "X",
7
description: "X coordinate"
8
}),
9
Schema.optionalElement(Schema.Number).annotations({
10
title: "Y",
11
description: "optional Y coordinate"
12
})
13
)
14
15
// Generating a JSON Schema from the tuple
16
console.log(JSONSchema.make(Point))
17
/*
18
Output:
19
{
20
'$schema': 'http://json-schema.org/draft-07/schema#',
21
type: 'array',
22
minItems: 1,
23
items: [
24
{ type: 'number', description: 'X coordinate', title: 'X' },
25
{
26
type: 'number',
27
description: 'optional Y coordinate',
28
title: 'Y'
29
}
30
],
31
additionalItems: false
32
}
33
*/

You can provide custom messages for missing fields or elements using the new missingMessage annotation.

Example (missing field)

1
import { Schema } from "@effect/schema"
2
3
const Person = Schema.Struct({
4
name: Schema.propertySignature(Schema.String).annotations({
5
missingMessage: () => "Name is required"
6
})
7
})
8
9
Schema.decodeUnknownSync(Person)({})
10
/*
11
Output:
12
Error: { readonly name: string }
13
└─ ["name"]
14
└─ Name is required
15
*/

Example (missing element)

1
import { Schema } from "@effect/schema"
2
3
const Point = Schema.Tuple(
4
Schema.element(Schema.Number).annotations({
5
missingMessage: () => "X coordinate is required"
6
}),
7
Schema.element(Schema.Number).annotations({
8
missingMessage: () => "Y coordinate is required"
9
})
10
)
11
12
Schema.decodeUnknownSync(Point)([], { errors: "all" })
13
/*
14
Output:
15
Error: readonly [number, number]
16
├─ [0]
17
│ └─ X coordinate is required
18
└─ [1]
19
└─ Y coordinate is required
20
*/

The individual APIs that were previously used to add annotations to schemas have been removed. This change was made because these individual annotation APIs did not provide significant value and were burdensome to maintain. Instead, you can now use the annotations method directly or the Schema.annotations API for a pipe-able approach.

Before

1
import { Schema } from "@effect/schema"
2
3
// Example of adding an identifier using a dedicated API
4
const schema = Schema.String.pipe(Schema.identifier("myIdentitifer"))

Now

1
import { Schema } from "@effect/schema"
2
3
// Directly using the annotations method
4
const schema = Schema.String.annotations({ identifier: "myIdentitifer" })
5
// or
6
const schema2 = Schema.String.pipe(
7
// Using the annotations function in a pipe-able format
8
Schema.annotations({ identifier: "myIdentitifer" })
9
)

Now the *Sync and asserts APIs throw a ParseError while before they was throwing a simple Error with a cause containing a ParseIssue

1
import { ParseResult, Schema } from "@effect/schema"
2
3
try {
4
Schema.decodeUnknownSync(Schema.String)(null)
5
} catch (e) {
6
console.log(ParseResult.isParseError(e)) // true
7
}
8
9
const asserts: (u: unknown) => asserts u is string = Schema.asserts(
10
Schema.String
11
)
12
try {
13
asserts(null)
14
} catch (e) {
15
console.log(ParseResult.isParseError(e)) // true
16
}

For all the details, head over to our changelog.