tapCodec

function tapCodec<TCodec>(codec, encodeTap, decodeTap?): TCodec;

Observes the values of a codec on both sides, without modifying them.

This function takes an existing codec and returns a new codec of the exact same type that:

  • Calls encodeTap with each value before encoding it.
  • Calls decodeTap (if provided) with each decoded value after decoding it.

Values are passed through unchanged, making this useful for adding validation guards, logging, or other read-only side effects. If either tap function throws, the corresponding operation is aborted and the error propagates to the caller.

Type Parameters

Type ParameterDescription
TCodec extends AnyCodecThe type of the codec being tapped. The returned codec has the same type.

Parameters

ParameterTypeDescription
codecTCodecThe codec whose values should be observed.
encodeTap(value) => voidA function called with each value before encoding. It may throw to abort encoding.
decodeTap?(value) => voidAn optional function called with each decoded value. It may throw to abort decoding.

Returns

TCodec

A new codec of the same type that observes its values.

Throws

Whatever error the tap functions throw, aborting the corresponding operation.

Example

Guarding both the encoded and decoded values of a u8 codec.

const codec = tapCodec(
    getU8Codec(),
    value => {
        if (value > 100) throw new Error('Value must not exceed 100');
    },
    value => {
        if (value === 0) throw new Error('Value must not be zero');
    },
);

Remarks

If only the input value needs observing, use tapEncoder. If only the decoded value needs observing, use tapDecoder. To observe the raw bytes instead of the values, use tapCodecBytes.

See

On this page