Skip to content

Commit 0c69b2e

Browse files
committed
docs: add nested error paths section to Schema.filter
1 parent a35fe10 commit 0c69b2e

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

content/src/content/docs/docs/schema/filters.mdx

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,81 @@ The error is formatted in a structured way using `ArrayFormatter`, allowing for
218218
[ArrayFormatter](/docs/schema/error-formatters/#arrayformatter).
219219
</Aside>
220220

221+
## Specifying Nested Error Paths
222+
223+
When defining custom validation logic with `Schema.filter`, you can precisely pinpoint where an error occurred within nested structures by specifying a nested path.
224+
225+
**Example** (Conditional Discount)
226+
227+
```ts twoslash
228+
import { Either, ParseResult, Schema } from "effect"
229+
230+
const Product = Schema.Struct({
231+
id: Schema.NonEmptyString,
232+
name: Schema.NonEmptyString,
233+
pricing: Schema.Struct({
234+
base: Schema.Number.pipe(Schema.greaterThanOrEqualTo(0)),
235+
discountPercentage: Schema.optional(
236+
Schema.Number.pipe(
237+
Schema.greaterThanOrEqualTo(0),
238+
Schema.lessThanOrEqualTo(100)
239+
)
240+
)
241+
})
242+
}).pipe(
243+
Schema.filter((input) => {
244+
const issues: Array<Schema.FilterIssue> = []
245+
246+
const MIN_PRICE_FOR_DISCOUNT = 50
247+
248+
if (
249+
input.pricing.discountPercentage !== undefined && input.pricing.discountPercentage > 0 &&
250+
input.pricing.base < MIN_PRICE_FOR_DISCOUNT
251+
) {
252+
issues.push({
253+
path: ["pricing", "discountPercentage"], // Report the error to the `pricing.discountPercentage` path
254+
message: `Discount can only be applied if base price is at least ${MIN_PRICE_FOR_DISCOUNT}.`
255+
})
256+
}
257+
return issues
258+
})
259+
)
260+
261+
262+
console.log(
263+
JSON.stringify(
264+
Schema.decodeUnknownEither(Product)({
265+
id: "P001",
266+
name: "Widget",
267+
pricing: {
268+
base: 25,
269+
discountPercentage: 20
270+
}
271+
}).pipe(
272+
Either.mapLeft((error) => ParseResult.ArrayFormatter.formatErrorSync(error))
273+
),
274+
null,
275+
2
276+
)
277+
)
278+
/**
279+
{
280+
"_id": "Either",
281+
"_tag": "Left",
282+
"left": [
283+
{
284+
"_tag": "Type",
285+
"path": [
286+
"pricing",
287+
"discountPercentage"
288+
],
289+
"message": "Discount can only be applied if base price is at least 50."
290+
}
291+
]
292+
}
293+
*/
294+
```
295+
221296
## Multiple Error Reporting
222297

223298
The `Schema.filter` API supports reporting multiple validation issues at once, which is especially useful in scenarios like form validation where several checks might fail simultaneously.

0 commit comments

Comments
 (0)