Hyperlinkv0.8.0-beta.28

Schema

Schema.middlewareEncodingfunctioneffect/Schema.ts:5212
middlewareEncoding<S, RE>

Intercepts the encoding pipeline of a schema.

Details

The provided function receives the current encoding Effect and ParseOptions, and returns a new Effect — potentially adding service requirements (RE), recovering from errors, or augmenting the result.

Example (Logging encode failures)

import { Effect, Schema } from "effect"

const Logged = Schema.String.pipe(
  Schema.middlewareEncoding((effect) =>
    Effect.tapError(effect, (issue) => Effect.log("encode failed", issue))
  )
)
Source effect/Schema.ts:521259 lines
export interface middlewareEncoding<S extends Constraint, RE> extends
  BottomLazy<
    S["ast"],
    middlewareEncoding<S, RE>,
    S["~type.parameters"],
    S["~type.mutability"],
    S["~type.optionality"],
    S["~type.constructor.default"],
    S["~encoded.mutability"],
    S["~encoded.optionality"]
  >
{
  readonly "Type": S["Type"]
  readonly "Encoded": S["Encoded"]
  readonly "DecodingServices": S["DecodingServices"]
  readonly "EncodingServices": RE
  readonly "~type.make.in": S["~type.make.in"]
  readonly "~type.make": S["~type.make"]
  readonly "Iso": S["Iso"]
  readonly schema: S
}

/**
 * Intercepts the encoding pipeline of a schema.
 *
 * **Details**
 *
 * The provided function receives the current encoding `Effect` and `ParseOptions`,
 * and returns a new `Effect` — potentially adding service requirements (`RE`),
 * recovering from errors, or augmenting the result.
 *
 * **Example** (Logging encode failures)
 *
 * ```ts
 * import { Effect, Schema } from "effect"
 *
 * const Logged = Schema.String.pipe(
 *   Schema.middlewareEncoding((effect) =>
 *     Effect.tapError(effect, (issue) => Effect.log("encode failed", issue))
 *   )
 * )
 * ```
 *
 * @see {@link catchEncoding} for a simpler error-recovery variant
 * @category encoding
 * @since 4.0.0
 */
export function middlewareEncoding<S extends Constraint, RE>(
  encode: (
    effect: Effect.Effect<Option_.Option<S["Encoded"]>, SchemaIssue.Issue, S["EncodingServices"]>,
    options: SchemaAST.ParseOptions
  ) => Effect.Effect<Option_.Option<S["Encoded"]>, SchemaIssue.Issue, RE>
) {
  return (schema: S): middlewareEncoding<S, RE> =>
    make(
      SchemaAST.middlewareEncoding(schema.ast, new SchemaTransformation.Middleware(identity, encode)),
      { schema }
    )
}
Referenced by 2 symbols