-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.ts
36 lines (34 loc) · 1.04 KB
/
validate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { BufferCodec } from "../types";
import { extend } from "./extend";
import { throwError, ThrownError } from "./assert";
/**
* Wraps a codec with an error condition.
* During both parsing and serializing, if `condition` returns `false`, an
* error is thrown.
*
* @example
* validate(
* string.nullTerminated(),
* s => s.length <= 10,
* s => `Maximum length is 10, but got ${s.length}`
* )
*
* @param codec The codec to validate
* @param condition Returns `true` if the condition is met
* @param errorMsg An error message to throw.
* This can be a string, Error object or a function that takes value and
* context and returns a string or Error object
*/
export const validate = <T, C>(
codec: BufferCodec<T, C>,
condition: (value: T, context?: C) => boolean,
errorMsg?: ThrownError<T, C>
): BufferCodec<T, C> => {
const assertion = (value: T, context?: C) => {
if (!condition(value, context)) {
throwError(errorMsg, value, context);
}
return value;
};
return extend(codec, assertion, assertion);
};