Last active
February 2, 2025 19:02
-
-
Save tim-smart/aa661fca3b01ac463830d7f30665f9e5 to your computer and use it in GitHub Desktop.
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
import type { StandardSchemaV1 } from "@standard-schema/spec" | |
import { NonEmptyArray } from "effect/Array" | |
import * as Data from "effect/Data" | |
import * as Effect from "effect/Effect" | |
import * as Predicate from "effect/Predicate" | |
export class StandardSchemaError extends Data.TaggedError( | |
"StandardSchemaError", | |
)<{ readonly issues: NonEmptyArray<StandardSchemaV1.Issue> }> { | |
static fromFailure( | |
failure: StandardSchemaV1.FailureResult, | |
): StandardSchemaError { | |
return new StandardSchemaError({ | |
issues: failure.issues as any, | |
}) | |
} | |
} | |
const resultToEffect = <O>( | |
result: StandardSchemaV1.Result<O>, | |
): Effect.Effect<O, StandardSchemaError> => | |
result.issues | |
? Effect.fail(StandardSchemaError.fromFailure(result)) | |
: Effect.succeed(result.value) | |
export const validate = <I, O>( | |
schema: StandardSchemaV1<I, O>, | |
input: I, | |
): Effect.Effect<O, StandardSchemaError> => | |
Effect.suspend(() => { | |
const result = schema["~standard"].validate(input) | |
return Predicate.isPromiseLike(result) | |
? Effect.flatMap( | |
Effect.promise(() => result), | |
resultToEffect, | |
) | |
: resultToEffect(result) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment