1 | 'use strict';
|
2 |
|
3 | function capitalize (string = '') {
|
4 | return string[0].toUpperCase() + string.slice(1);
|
5 | }
|
6 |
|
7 | function indent (depth = 0, width = 2) {
|
8 | return ' '.repeat(depth * width);
|
9 | }
|
10 |
|
11 | function generateValidator (object, {
|
12 | flattenTypes = false,
|
13 | functionName = 'validate',
|
14 | loopVariables = [ 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'x', 'y', 'z' ],
|
15 | returnPromise = false,
|
16 | variable = 'object',
|
17 | width = 2,
|
18 | } = {}) {
|
19 | function validatorIterator (chunk, name, depth = 1) {
|
20 | let validator = '';
|
21 |
|
22 | if (typeof chunk === 'undefined' || chunk === null) {
|
23 | return validator;
|
24 | } else if (Array.isArray(chunk)) {
|
25 | validator += `${ indent(depth, width) }expect(${ name }).be.instanceOf(Array);\n`;
|
26 | if (chunk.length) {
|
27 |
|
28 | const loop = loopVariables[depth];
|
29 | validator += `${ indent(depth, width) }for (let ${ loop } = 0; ${ loop } < ${ name }.length; ${ loop }++) {\n`;
|
30 | validator += validatorIterator(chunk[0], `${ name }[${ loop }]`, depth + 1);
|
31 | validator += `${ indent(depth, width) }}\n`;
|
32 | }
|
33 | } else if (typeof chunk === 'object') {
|
34 | validator += `${ indent(depth, width) }expect(${ name }).to.be.an.instanceOf(Object);\n`;
|
35 | for (const element in chunk) {
|
36 | validator += `${ indent(depth, width) }expect(${ Number(name) }).to.have.property('${ element }');\n`;
|
37 | validator += validatorIterator(chunk[element], `${ name }.${ element }`, depth);
|
38 | }
|
39 | } else {
|
40 | let type = capitalize(typeof chunk);
|
41 | if (flattenTypes && (type !== 'Boolean' && type !== 'Number')) {
|
42 | type = 'String';
|
43 | }
|
44 | validator += `${ indent(depth, width) }expect(${ name }).to.be.an.instanceOf(${ type });\n`;
|
45 | }
|
46 | return validator;
|
47 | }
|
48 |
|
49 | const validator = `const ${ functionName } = function(${ variable }) {
|
50 | ${ validatorIterator(object, variable) }
|
51 | return ${ returnPromise ? 'Promise.resolve(true)' : 'true' };
|
52 | };
|
53 | `;
|
54 |
|
55 | return validator;
|
56 | }
|
57 |
|
58 | module.exports = generateValidator;
|