#値をパースする
リクエストボディ、JSON ファイル、環境変数など、プログラムの外から来るデータは、バリデーションするまでは unknown です。
parse はそのような値をスキーマに照らしてバリデーションし、その結果を Result として返します。
#parse でバリデーションする
parse(schema, value)ケースを選ぶと、その流れだけを追えますparse は、Standard Schema を実装したスキーマであれば何でも受け付けます。Standard Schema は、Zod、Valibot、ArkType などのバリデーションライブラリがサポートしている共通インターフェースです。
このページの例では Zod を使います。
import { import Result Result } from '@praha/byethrow';
import { import z z } from 'zod';
const const User: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>
User = import z z .function object<{
name: z.ZodString;
email: z.ZodEmail;
}>(shape?: {
name: z.ZodString;
email: z.ZodEmail;
} | undefined, params?: string | {
error?: string | z.core.$ZodErrorMap<NonNullable<z.core.$ZodIssueInvalidType<unknown> | z.core.$ZodIssueUnrecognizedKeys>> | undefined;
message?: string | undefined | undefined;
} | undefined): z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>
object ({
name: z.ZodString name : import z z .function string(params?: string | z.core.$ZodStringParams): z.ZodString (+1 overload) string ()._ZodString<$ZodStringInternals<string>>.min(minLength: number, params?: string | z.core.$ZodCheckMinLengthParams): z.ZodString min (1),
email: z.ZodEmail email : import z z .function email(params?: string | z.core.$ZodEmailParams): z.ZodEmail email (),
});
const const result: Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1.Issue[]>
result = import Result Result .function parse<z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>>(schema: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>, value: unknown): Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)
Parses a value using a
https://github.com/standard-schema/standard-schema Standard Schema
compatible schema.
Returns a
Result
with the parsed value on success or validation errors on failure.
@typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@exampleBasic Usage
import { Result } from '@praha/byethrow';
import { z } from 'zod';
const schema = z.object({ name: z.string() });
const result = Result.parse(schema, { name: 'John' });
// Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
@exampleCurried Usage
import { Result } from '@praha/byethrow';
import { z } from 'zod';
const schema = z.object({ name: z.string() });
const parser = Result.parse(schema);
const result = parser({ name: 'John' });
// Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
@categoryUtilities parse (const User: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>
User , { name: string name : 'Alice', email: string email : 'alice@example.com' });
// 型: Result.Result<{ name: string; email: string }, ReadonlyArray<StandardSchemaV1.Issue>>値がスキーマに一致する場合、結果はパースされた値を持つ Success になり、その値はスキーマに従って型付けされます。
一致しない場合、結果はバリデーションの問題(issue)の一覧を持つ Failure になります。
#バリデーションの問題を読み取る
各 issue は message と、不正なプロパティを指す path(省略される場合もあります)を持ちます。
const const result: Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1.Issue[]>
result = import Result Result .function parse<z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>>(schema: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>, value: unknown): Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)
Parses a value using a
https://github.com/standard-schema/standard-schema Standard Schema
compatible schema.
Returns a
Result
with the parsed value on success or validation errors on failure.
@typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@exampleBasic Usage
import { Result } from '@praha/byethrow';
import { z } from 'zod';
const schema = z.object({ name: z.string() });
const result = Result.parse(schema, { name: 'John' });
// Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
@exampleCurried Usage
import { Result } from '@praha/byethrow';
import { z } from 'zod';
const schema = z.object({ name: z.string() });
const parser = Result.parse(schema);
const result = parser({ name: 'John' });
// Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
@categoryUtilities parse (const User: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>
User , { name: string name : '', email: string email : 'not an email' });
if (import Result Result .function isFailure<Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>>(result: Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1.Issue[]>): result is Result.Failure<readonly StandardSchemaV1.Issue[]>
Type guard to check if a
Result
is a
Failure
.
@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Failure , otherwise false.@exampleimport { Result } from '@praha/byethrow';
const result: Result.Result<number, string> = { type: 'Failure', error: 'Something went wrong' };
if (Result.isFailure(result)) {
console.error(result.error); // Safe access to error
}
@categoryType Guards isFailure (const result: Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1.Issue[]>
result )) {
for (const const issue: StandardSchemaV1.Issue issue of const result: Result.Failure<readonly StandardSchemaV1.Issue[]> result .error: readonly StandardSchemaV1.Issue[] error ) {
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log (const issue: StandardSchemaV1.Issue issue .StandardSchemaV1<Input = unknown, Output = Input>.Issue.path?: readonly (PropertyKey | StandardSchemaV1.PathSegment)[] | undefinedThe path of the issue, if any.
path , const issue: StandardSchemaV1.Issue issue .StandardSchemaV1<Input = unknown, Output = Input>.Issue.message: stringThe error message of the issue.
message );
}
}#パイプラインの中で parse を使う
スキーマだけを渡して呼び出すと、parse は引数をバリデーションする関数を返します。
この形はパイプラインに自然に組み込めます。パイプラインについては「pipe の基本」で学びます。
import { import Result Result } from '@praha/byethrow';
const const parseJson: (text: string) => Result.Result<unknown, Error> parseJson = import Result Result .function fn<(text: string) => unknown, Error>(options: {
try: (text: string) => unknown;
catch: (error: unknown) => Error;
}): (text: string) => Result.Result<unknown, Error> (+3 overloads)
Wraps a function that may throw and returns a new function that returns a
Result
or
ResultAsync
.
You can use either a custom catch handler or rely on the safe: true option
to assume the function cannot throw.
@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA new function that returns a Result or ResultAsync wrapping the original function's return value or the caught error.@exampleSync try-catch
import { Result } from '@praha/byethrow';
const fn = Result.fn({
try: (x: number) => {
if (x < 0) throw new Error('Negative!');
return x * 2;
},
catch: (error) => new Error('Oops!', { cause: error }),
});
const result = fn(5); // Result.Result<number, Error>
@exampleSync safe
import { Result } from '@praha/byethrow';
const fn = Result.fn({
safe: true,
try: (x: number) => x + 1,
});
const result = fn(1); // Result.Result<number, never>
@exampleAsync try-catch
import { Result } from '@praha/byethrow';
const fn = Result.fn({
try: async (id: string) => await fetch(`/api/data/${id}`),
catch: (error) => new Error('Oops!', { cause: error }),
});
const result = await fn('abc'); // Result.ResultAsync<Response, Error>
@exampleAsync safe
import { Result } from '@praha/byethrow';
const fn = Result.fn({
safe: true,
try: async () => await Promise.resolve('ok'),
});
const result = await fn(); // Result.ResultAsync<string, never>
@categoryCreators fn ({
try: (text: string) => unknown try : (text: string text : string) => var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.
@paramtext A valid JSON string.@paramreviver A function that transforms the results. This function is called for each member of the object.
If a member contains nested objects, the nested objects are transformed before the parent object is.@throws{SyntaxError} If text is not valid JSON. parse (text: string text ) as unknown,
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Invalid JSON', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
const const parseUser: (text: string) => Result.Result<{
name: string;
email: string;
}, Error | readonly StandardSchemaV1.Issue[]>
parseUser = (text: string text : string) => import Result Result .function pipe<Result.Result<unknown, Error>, Result.Result<{
name: string;
email: string;
}, Error | readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>>(a: Result.Result<unknown, Error>, ab: (a: Result.Result<unknown, Error>) => Result.Result<{
name: string;
email: string;
}, Error | readonly StandardSchemaV1.Issue[]>): Result.Result<{
name: string;
email: string;
}, Error | readonly StandardSchemaV1.Issue[]> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
const parseJson: (text: string) => Result.Result<unknown, Error> parseJson (text: string text ),
import Result Result .function andThen<Result.Result<unknown, Error>, Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>>(fn: (a: unknown) => Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1.Issue[]>): (result: Result.Result<unknown, Error>) => Result.Result<{
name: string;
email: string;
}, Error | readonly StandardSchemaV1.Issue[]> (+1 overload)
Chains the next computation using the success value of a
Result
or
ResultAsync
.
If the original result is a
Failure
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThen((x) => Result.succeed(x * 2)),
);
// result: { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.fail('error: ' + x)),
);
// result: { type: 'Failure', error: 'error: 3' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (import Result Result .function parse<z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>>(schema: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>): (value: unknown) => Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)
Parses a value using a
https://github.com/standard-schema/standard-schema Standard Schema
compatible schema.
Returns a
Result
with the parsed value on success or validation errors on failure.
@typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@exampleBasic Usage
import { Result } from '@praha/byethrow';
import { z } from 'zod';
const schema = z.object({ name: z.string() });
const result = Result.parse(schema, { name: 'John' });
// Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
@exampleCurried Usage
import { Result } from '@praha/byethrow';
import { z } from 'zod';
const schema = z.object({ name: z.string() });
const parser = Result.parse(schema);
const result = parser({ name: 'John' });
// Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
@categoryUtilities parse (const User: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>
User )),
);issue の一覧を独自のエラー型に置き換えるには、mapError を使います。
import { import Result Result } from '@praha/byethrow';
class class ValidationError ValidationError extends var Error: ErrorConstructor Error {
override readonly ValidationError.name: "ValidationError" name = 'ValidationError';
}
const const validateUser: (input: unknown) => Result.Result<{
name: string;
email: string;
}, ValidationError>
validateUser = (input: unknown input : unknown) => import Result Result .function pipe<unknown, Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, Result.Result<{
name: string;
email: string;
}, ValidationError>>(a: unknown, ab: (a: unknown) => Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1.Issue[]>, bc: (b: Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1.Issue[]>) => Result.Result<{
name: string;
email: string;
}, ValidationError>): Result.Result<{
name: string;
email: string;
}, ValidationError> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
input: unknown input ,
import Result Result .function parse<z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>>(schema: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>): (value: unknown) => Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]> (+1 overload)
Parses a value using a
https://github.com/standard-schema/standard-schema Standard Schema
compatible schema.
Returns a
Result
with the parsed value on success or validation errors on failure.
@typeParamS - The Standard Schema V1 compatible schema type.@returnsA Result with the parsed value or validation errors.@exampleBasic Usage
import { Result } from '@praha/byethrow';
import { z } from 'zod';
const schema = z.object({ name: z.string() });
const result = Result.parse(schema, { name: 'John' });
// Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
@exampleCurried Usage
import { Result } from '@praha/byethrow';
import { z } from 'zod';
const schema = z.object({ name: z.string() });
const parser = Result.parse(schema);
const result = parser({ name: 'John' });
// Result.Result<{ name: string }, ReadonlyArray<StandardSchemaV1.Issue>>
@categoryUtilities parse (const User: z.ZodObject<{
name: z.ZodString;
email: z.ZodEmail;
}, z.core.$strip>
User ),
import Result Result .function mapError<Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1<Input = unknown, Output = Input>.Issue[]>, ValidationError>(fn: (a: readonly StandardSchemaV1.Issue[]) => ValidationError): (result: Result.Result<{
name: string;
email: string;
}, readonly StandardSchemaV1.Issue[]>) => Result.Result<{
name: string;
email: string;
}, ValidationError> (+1 overload)
Applies a transformation function to the error value of a
Result
or
ResultAsync
.
If the input is a
Success
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamE2 - The transformed error value type.@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('NotFound'),
Result.mapError((error) => new Error(error)),
);
// { type: 'Failure', error: Error('NotFound') }
@exampleSuccess Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(123),
Result.mapError((error) => new Error(error)),
);
// { type: 'Success', value: 123 }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators mapError ((issues: readonly StandardSchemaV1.Issue[] issues ) => new constructor ValidationError(message?: string, options?: ErrorOptions): ValidationError (+1 overload) ValidationError ('Invalid user', { ErrorOptions.cause?: unknown cause : issues: readonly StandardSchemaV1.Issue[] issues })),
);
parse は同期的なバリデーションにのみ対応しています。
スキーマが非同期のバリデーション(例えば非同期の refinement)を行う場合、parse は TypeError を投げます。
#リファレンス
| API | 用途 |
|---|---|
| parse(schema, value) | Standard Schema で値をバリデーションする |
