misskey/src/api/validator.ts

60 lines
1.1 KiB
TypeScript
Raw Normal View History

2017-03-02 01:06:16 +09:00
import * as mongo from 'mongodb';
type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'object';
2017-03-02 01:11:30 +09:00
export default <T>(value: any, isRequired: boolean, type: Type, validator?: (any) => boolean): [T, string] => {
2017-03-02 01:06:16 +09:00
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;
}
2017-03-02 01:11:30 +09:00
if (validator) {
if (!validator(value)) {
return [null, 'invalid-format'];
}
}
2017-03-02 01:06:16 +09:00
return [value, null];
};