diff options
| author | syuilo <syuilotan@yahoo.co.jp> | 2017-03-02 01:06:16 +0900 |
|---|---|---|
| committer | syuilo <syuilotan@yahoo.co.jp> | 2017-03-02 01:06:16 +0900 |
| commit | 73deef0ca7038f9a88f9cb36e6c1b17c354a3a35 (patch) | |
| tree | 389afa5d9b846782631b5dcef4b0711debeab959 /src/api | |
| parent | [API] Fix bug (diff) | |
| download | sharkey-73deef0ca7038f9a88f9cb36e6c1b17c354a3a35.tar.gz sharkey-73deef0ca7038f9a88f9cb36e6c1b17c354a3a35.tar.bz2 sharkey-73deef0ca7038f9a88f9cb36e6c1b17c354a3a35.zip | |
wip
Diffstat (limited to 'src/api')
| -rw-r--r-- | src/api/validator.ts | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/src/api/validator.ts b/src/api/validator.ts new file mode 100644 index 0000000000..d75fe6420b --- /dev/null +++ b/src/api/validator.ts @@ -0,0 +1,53 @@ +import * as mongo from 'mongodb'; + +type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'object'; + +export default <T>(value: any, isRequired: boolean, type: Type): [T, string] => { + if (value === undefined || value === null) { + if (isRequired) { + return [null, 'is-required'] + } else { + return [null, null] + } + } + + switch (type) { + case 'id': + if (typeof value != 'string' || !mongo.ObjectID.isValid(value)) { + return [null, 'incorrect-id']; + } + break; + + case 'string': + if (typeof value != 'string') { + return [null, 'must-be-a-string']; + } + break; + + case 'number': + if (!Number.isFinite(value)) { + return [null, 'must-be-a-number']; + } + break; + + case 'boolean': + if (typeof value != 'boolean') { + return [null, 'must-be-an-boolean']; + } + break; + + case 'array': + if (!Array.isArray(value)) { + return [null, 'must-be-an-array']; + } + break; + + case 'object': + if (typeof value != 'object') { + return [null, 'must-be-an-onject']; + } + break; + } + + return [value, null]; +}; |