phantasy-validation
Version:
Type-safe validation
55 lines (48 loc) • 1.56 kB
Flow
// @flow
import type { Node } from 'validated/schema';
import * as t from 'validated/schema';
import { Result } from 'phantasy';
import { validate as jsonValidate } from 'validated/json5';
import { validate as valValidate } from 'validated/object';
export type RuntimeType<T> = Node<T>
export type ValidationError = {
message: string,
validated: mixed,
originalError: Error
}
/**
* `validationError :: Error -> mixed -> ValidationError`
*/
export function validationError(err: Error, validated: mixed): ValidationError {
return {
message: err.message,
validated,
originalError: err
};
}
/**
* `validateJson :: Node t -> string -> Result t ValidationError`
*/
export function validateJson<T>(schema: Node<T>, json: string): Result<T, ValidationError> {
return Result.fromThrowable(() => jsonValidate(schema, json))
.handleError(err => Result.Err(validationError(err, json)));
}
/**
* `validateValue :: Node t -> mixed -> Result t ValidationError`
*/
export function validateValue<T>(schema: Node<T>, value: mixed): Result<T, ValidationError> {
return Result.fromThrowable(() => valValidate(schema, value))
.handleError(err => Result.Err(validationError(err, value)));
}
// run-time types
export const any = t.any;
export const bool = t.boolean;
export const num = t.number;
export const str = t.string;
export const enumeration = t.enumeration;
export const array = t.arrayOf;
export const obj = t.object;
export const partial = t.partialObject;
export const maybe = t.maybe;
export const union = t.oneOf;
export const ref = t.ref;