2019-07-11 12:23:57 +03:00
|
|
|
import * as t from "io-ts";
|
|
|
|
import { pipe } from "fp-ts/lib/pipeable";
|
|
|
|
import { fold } from "fp-ts/lib/Either";
|
2019-07-22 00:09:45 +03:00
|
|
|
import { noop } from "./utils";
|
2019-07-22 13:09:05 +03:00
|
|
|
import deepDiff from "deep-diff";
|
2019-07-22 00:09:45 +03:00
|
|
|
|
|
|
|
// From io-ts/lib/PathReporter
|
|
|
|
function stringify(v) {
|
|
|
|
if (typeof v === "function") {
|
|
|
|
return t.getFunctionName(v);
|
|
|
|
}
|
|
|
|
if (typeof v === "number" && !isFinite(v)) {
|
|
|
|
if (isNaN(v)) {
|
|
|
|
return "NaN";
|
|
|
|
}
|
|
|
|
return v > 0 ? "Infinity" : "-Infinity";
|
|
|
|
}
|
|
|
|
return JSON.stringify(v);
|
|
|
|
}
|
|
|
|
|
|
|
|
// From io-ts/lib/PathReporter
|
|
|
|
// tslint:disable
|
|
|
|
function getContextPath(context) {
|
|
|
|
return context
|
|
|
|
.map(function(_a) {
|
|
|
|
var key = _a.key,
|
|
|
|
type = _a.type;
|
|
|
|
return key + ": " + type.name;
|
|
|
|
})
|
|
|
|
.join("/");
|
|
|
|
}
|
|
|
|
// tslint:enable
|
|
|
|
|
|
|
|
const report = fold((errors: any) => {
|
|
|
|
return errors.map(err => {
|
|
|
|
if (err.message) return err.message;
|
|
|
|
const context = err.context.map(c => c.key).filter(k => k && !k.startsWith("{"));
|
2019-07-22 13:50:41 +03:00
|
|
|
const value = stringify(err.value);
|
|
|
|
return value === undefined
|
|
|
|
? `<${context.join("/")}> is required`
|
|
|
|
: `Invalid value <${stringify(err.value)}> supplied to <${context.join("/")}>`;
|
2019-07-22 00:09:45 +03:00
|
|
|
});
|
|
|
|
}, noop);
|
2019-07-11 12:23:57 +03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Validates the given value against the given schema while also disallowing extra properties
|
|
|
|
* See: https://github.com/gcanti/io-ts/issues/322
|
|
|
|
*/
|
2019-07-22 13:09:05 +03:00
|
|
|
export function validateStrict(schema: t.HasProps, value: any): string[] | null {
|
|
|
|
const validationResult = t.exact(schema).decode(value);
|
2019-07-11 12:23:57 +03:00
|
|
|
return pipe(
|
|
|
|
validationResult,
|
|
|
|
fold(
|
2019-07-22 00:09:45 +03:00
|
|
|
err => report(validationResult),
|
2019-07-11 12:23:57 +03:00
|
|
|
result => {
|
|
|
|
// Make sure there are no extra properties
|
|
|
|
if (JSON.stringify(value) !== JSON.stringify(result)) {
|
2019-07-22 13:09:05 +03:00
|
|
|
const diff = deepDiff(result, value);
|
|
|
|
const errors = diff.filter(d => d.kind === "N").map(d => `Unknown property <${d.path.join(".")}>`);
|
|
|
|
return errors.length ? errors : ["Found unknown properties"];
|
2019-07-11 12:23:57 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
},
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|