source: node_modules/@standard-schema/utils/README.md

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 2.3 KB
RevLine 
[a762898]1# Standard Schema Utils
2
3There are two common tasks that third-party libraries perform after validation fails. The first is to flatten the issues by creating a dot path to more easily associate the issues with the input data. This is commonly used in form libraries. The second is to throw an error that contains all the issue information. To simplify both tasks, Standard Schema also ships a utils package that provides a `getDotPath` function and a `SchemaError` class.
4
5```sh
6npm install @standard-schema/utils # npm
7yarn add @standard-schema/utils # yarn
8pnpm add @standard-schema/utils # pnpm
9bun add @standard-schema/utils # bun
10deno add jsr:@standard-schema/utils # deno
11```
12
13## Get Dot Path
14
15To generate a dot path, simply pass an issue to the `getDotPath` function. If the issue does not contain a path or the path contains a key that is not of type `string` or `number`, the function returns `null`.
16
17```ts
18import type { StandardSchemaV1 } from "@standard-schema/spec";
19import { getDotPath } from "@standard-schema/utils";
20
21async function getFormErrors(schema: StandardSchemaV1, data: unknown) {
22 const result = await schema["~standard"].validate(data);
23 const formErrors: string[] = [];
24 const fieldErrors: Record<string, string[]> = {};
25 if (result.issues) {
26 for (const issue of result.issues) {
27 const dotPath = getDotPath(issue);
28 if (dotPath) {
29 if (fieldErrors[dotPath]) {
30 fieldErrors[dotPath].push(issue.message);
31 } else {
32 fieldErrors[dotPath] = [issue.message];
33 }
34 } else {
35 formErrors.push(issue.message);
36 }
37 }
38 }
39 return { formErrors, fieldErrors };
40}
41```
42
43## Schema Error
44
45To throw an error that contains all issue information, simply pass the issues of the failed schema validation to the `SchemaError` class. The `SchemaError` class extends the `Error` class with an `issues` property that contains all the issues.
46
47```ts
48import type { StandardSchemaV1 } from "@standard-schema/spec";
49import { SchemaError } from "@standard-schema/utils";
50
51async function validateInput<TSchema extends StandardSchemaV1>(
52 schema: TSchema,
53 data: unknown,
54): Promise<StandardSchemaV1.InferOutput<TSchema>> {
55 const result = await schema["~standard"].validate(data);
56 if (result.issues) {
57 throw new SchemaError(result.issues);
58 }
59 return result.value;
60}
61```
Note: See TracBrowser for help on using the repository browser.