tapEncoder

function tapEncoder<TEncoder>(encoder, tap): TEncoder;

Observes the input value of an encoder before it is encoded, without modifying it.

This function takes an existing encoder and returns a new encoder of the exact same type that calls the provided tap function with each value before delegating to the original encoder. The value is passed through unchanged, making this useful for adding validation guards, logging, or other read-only side effects on the input value.

If the tap function throws, the encoding is aborted and the error propagates to the caller.

Type Parameters

Type ParameterDescription
TEncoder extends AnyEncoderThe type of the encoder being tapped. The returned encoder has the same type.

Parameters

ParameterTypeDescription
encoderTEncoderThe encoder whose input value should be observed.
tap(value) => voidA function called with each value before encoding. It may throw to abort encoding.

Returns

TEncoder

A new encoder of the same type that observes its input value before encoding.

Throws

Whatever error the tap function throws, aborting the encoding.

Example

Guarding the input value of a u8 encoder.

const encoder = tapEncoder(getU8Encoder(), value => {
    if (value > 100) throw new Error('Value must not exceed 100');
});
encoder.encode(42); // 0x2a
encoder.encode(200); // Throws 'Value must not exceed 100'

Remarks

The tap fires from within the encoder's write step. For variable-size encoders, this means the encoded size is computed from the unvalidated value (via getSizeFromValue) before the tap runs, so a custom getSizeFromValue that rejects the value will throw before the tap has a chance to.

To observe the encoded bytes instead of the input value, use tapEncoderBytes.

See

On this page