Skip to content

Instantly share code, notes, and snippets.

@intech
Last active October 8, 2020 09:39
Show Gist options
  • Select an option

  • Save intech/eabd6ef917852fea9a2112e675a9068f to your computer and use it in GitHub Desktop.

Select an option

Save intech/eabd6ef917852fea9a2112e675a9068f to your computer and use it in GitHub Desktop.
const Validator = require("fastest-validator");
const v = new Validator();
const schema = [{
foo: "string|min:5",
bar: "number[]",
o: {
type: "object",
props: {
a: "string|max:24"
}
}
}, {
array: [
{ foo: { type: "string", min: 5 }},
{ bar: "number[]" }
]
}, {
foo: { type: "string", min: 5 },
bar: { type: "array", items: "number" }
}];
function parse(schema) {
for (let [name, rule] of Object.entries(schema)) {
if (Array.isArray(rule)) {
if (!rule.length) throw new Error("Invalid schema.");
rule = {
type: "multi",
rules: parse(rule)
};
} else if (typeof rule === "object") {
rule = parse(rule);
} else if (typeof rule === "string") {
rule = v.parseShortHand(rule);
}
schema[name] = rule;
}
return schema;
}
for(const test of schema) {
console.log("".padEnd(120,"-"));
console.count("test");
console.dir(test, {colors: true, depth: 5});
console.log();
console.dir(parse(test), {colors: true, depth: 5});
}

test: 1

// input:
{
  foo: 'string|min:5',
  bar: 'number[]',
  o: { type: 'object', props: { a: 'string|max:24' } }
}
// output:
{
  foo: { type: 'string', min: 5 },
  bar: { type: 'array', items: 'number' },
  o: {
    type: { type: 'object' },
    props: { a: { type: 'string', max: 24 } }
  }
}

test: 2

// input:
{
  array: [
    { foo: { type: 'string', min: 5 } },
    { bar: 'number[]' }
  ]
}
// output:
{
  array: {
    type: 'multi',
    rules: [
      { foo: { type: { type: 'string' }, min: 5 } },
      { bar: { type: 'array', items: 'number' } }
    ]
  }
}

test: 3

// input:
{
  foo: { type: 'string', min: 5 },
  bar: { type: 'array', items: 'number' }
}
// output:
{
  foo: { type: { type: 'string' }, min: 5 },
  bar: { type: { type: 'array' }, items: { type: 'number' } }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment