Hyperlinkv0.8.0-beta.28

SchemaTransformation

SchemaTransformation.Middlewareclasseffect/SchemaTransformation.ts:69
Middleware<T, E, RDE, RDT, RET, REE>

Middleware that wraps the entire parsing Effect pipeline for both decode and encode directions.

When to use

Use when you need a schema middleware to catch or recover from parsing errors (e.g. Schema.catchDecoding), run side effects around the parsing pipeline, or access the full Effect rather than a single decoded value.

Details

Unlike Transformation, which operates on individual values via Getter, Middleware receives the full Effect produced by the inner schema and can intercept, modify, retry, or replace it.

  • decode receives an Effect<Option<E>, Issue, RDE> and returns Effect<Option<T>, Issue, RDT>.
  • encode receives an Effect<Option<T>, Issue, RET> and returns Effect<Option<E>, Issue, REE>.
  • flip() swaps the decode and encode functions, producing a Middleware<E, T, ...>.

Typically constructed indirectly via Schema.middlewareDecoding or Schema.middlewareEncoding rather than instantiating this class directly.

Example (Creating a middleware that falls back on decode failure)

import { Effect, Option, SchemaTransformation } from "effect"

const fallback = new SchemaTransformation.Middleware(
  (effect) => Effect.catch(effect, () => Effect.succeed(Option.some("fallback"))),
  (effect) => effect
)
export class Middleware<in out T, in out E, RDE, RDT, RET, REE> {
  readonly _tag = "Middleware"
  readonly decode: (
    effect: Effect.Effect<Option.Option<E>, SchemaIssue.Issue, RDE>,
    options: SchemaAST.ParseOptions
  ) => Effect.Effect<Option.Option<T>, SchemaIssue.Issue, RDT>
  readonly encode: (
    effect: Effect.Effect<Option.Option<T>, SchemaIssue.Issue, RET>,
    options: SchemaAST.ParseOptions
  ) => Effect.Effect<Option.Option<E>, SchemaIssue.Issue, REE>

  constructor(
    decode: (
      effect: Effect.Effect<Option.Option<E>, SchemaIssue.Issue, RDE>,
      options: SchemaAST.ParseOptions
    ) => Effect.Effect<Option.Option<T>, SchemaIssue.Issue, RDT>,
    encode: (
      effect: Effect.Effect<Option.Option<T>, SchemaIssue.Issue, RET>,
      options: SchemaAST.ParseOptions
    ) => Effect.Effect<Option.Option<E>, SchemaIssue.Issue, REE>
  ) {
    this.decode = decode
    this.encode = encode
  }
  flip(): Middleware<E, T, RET, REE, RDE, RDT> {
    return new Middleware(this.encode, this.decode)
  }
}
Referenced by 3 symbols