-
Notifications
You must be signed in to change notification settings - Fork 24
/
validate.js
72 lines (59 loc) 路 2.2 KB
/
validate.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* @flow */
import BigNumber from 'bn.js';
import isPlainObject from 'lodash.isplainobject';
import { isValidAddress, makeAssert } from '@colony/colony-js-utils';
import type { ParamTypes, ParamTypePairs } from '../flowtypes';
const assert = makeAssert('Validation failed');
const TYPE_MAP = new Map([
['address', isValidAddress],
['string', value => typeof value === 'string'], // empty strings are allowed
['number', value => typeof value === 'number' || BigNumber.isBN(value)],
['boolean', value => typeof value === 'boolean'],
]);
export const validateParam = (
key: string,
type: ParamTypes,
value: any,
): boolean => {
assert(TYPE_MAP.has(type), `Parameter type "${type}" not defined`);
const check = TYPE_MAP.get(type);
return assert(
check != null && check(value),
`Parameter "${key}" expected a value of type "${type}"`,
);
};
const isValidMethodParams = (paramPairs: any): boolean =>
Array.isArray(paramPairs) &&
paramPairs.every(
param =>
Array.isArray(param) &&
param.length === 2 &&
typeof param[0] === 'string',
);
const isSameSize = (input: Object, paramPairs: ParamTypePairs) =>
Object.getOwnPropertyNames(input).length === paramPairs.length;
const isParamsEmpty = paramPairs =>
paramPairs == null || (Array.isArray(paramPairs) && paramPairs.length === 0);
const isInputEmpty = input =>
input == null || (isPlainObject(input) && Object.keys(input).length === 0);
/**
* Pure function
* Given parameters (as an object with named parameters, but potentially any
* kind of invalid input) and contract method parameters, validate each
* parameter against the expected type, throwing errors or returning true.
*/
export default function validate(input: any, paramPairs: any): boolean {
if (isParamsEmpty(paramPairs) && isInputEmpty(input)) return true;
assert(isPlainObject(input), 'Expected parameters as an object');
assert(
isValidMethodParams(paramPairs),
'Expected method parameters as an array of name/type tuples',
);
assert(
isSameSize(input, paramPairs),
'Mismatching parameters/method parameters sizes',
);
return paramPairs.every(([paramName, paramType]) =>
validateParam(paramName, paramType, input[paramName]),
);
}