UNPKG

@jkcfg/std

Version:

jk standard library

49 lines (48 loc) 1.67 kB
import { log, Format } from '../index'; import * as host from '@jkcfg/std/internal/host'; // magic module import * as param from '../param'; import { formatError, normaliseResult } from '../validation'; import { valuesFormatFromPath } from '../read'; function reduce(results) { return results.reduce((a, b) => { if (a == 'ok') return b; if (b == 'ok') return a; return Array.prototype.concat(a, b); }, 'ok'); } export default function validate(fn) { const inputFiles = param.Object('jk.validate.input', {}); const files = Object.keys(inputFiles); function validateValue(v) { return Promise.resolve(fn(v)).then(normaliseResult); } async function validateFile(path) { const format = valuesFormatFromPath(path); const obj = await host.read(path, { format }); switch (format) { case Format.YAMLStream: case Format.JSONStream: const results = obj.map(validateValue); const resolvedResults = await Promise.all(results); return { path, result: reduce(resolvedResults) }; default: const result = await validateValue(obj); return { path, result }; } } const objects = files.map(validateFile); Promise.all(objects).then((results) => { for (const { path, result } of results) { if (result === 'ok') { log(`${path}: ok`); } else { for (const err of result) { log(formatError(path, err)); } } } }); }