tapCodec
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
encodeTapwith 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 Parameter | Description |
|---|---|
TCodec extends AnyCodec | The type of the codec being tapped. The returned codec has the same type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
codec | TCodec | The codec whose values should be observed. |
encodeTap | (value) => void | A function called with each value before encoding. It may throw to abort encoding. |
decodeTap? | (value) => void | An 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.
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.