// @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 = Node 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(schema: Node, json: string): Result { return Result.fromThrowable(() => jsonValidate(schema, json)) .handleError(err => Result.Err(validationError(err, json))); } /** * `validateValue :: Node t -> mixed -> Result t ValidationError` */ export function validateValue(schema: Node, value: mixed): Result { 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;