All files / app index.js

59.57% Statements 56/94
45.45% Branches 35/77
73.33% Functions 11/15
60% Lines 51/85

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 1561x 1x     2x 2x 2x 2x 2x     6x   2x 2x   2x       2x   2x   2x 2x 2x             4x 2x                 10x 10x                             10x 10x   10x 10x 10x                                                               10x 10x 10x   10x 10x 8x 8x 8x     10x         10x     10x 10x 10x         1x 2x 1x 1x 1x   1x 1x 1x 1x 1x             1x 1x                 1x            
const swaggerParser = require('@apidevtools/swagger-parser');
const validator = require('./validator');
 
function methodValidator(swagger, pathName, methodName, basePath) {
    Eif (!basePath) basePath = swagger.basePath || '';
    const path = swagger.paths[pathName.slice(basePath.length)];
    const method = path[methodName];
    const requestBody = method.requestBody?.content?.['application/json']; // openapi 3
    const params = [requestBody && {schema: requestBody.schema, in: 'body'}]
        .concat(path.parameters)
        .concat(method.parameters)
        .filter(x => x)
        .map(param => {
            const schema = param.schema || (({name, in: ignore, ...schema}) => schema)(param);
            Iif (['query', 'header', 'path'].indexOf(param.in) !== -1) {
                param.validate = validator.primitive(schema);
            } else Iif (param.in === 'formData') {
                if (param.type === 'file') param.validate = validator.file(schema);
                else param.validate = validator.primitive(schema);
            } else {
                param.validate = validator.json(schema);
            }
            return param;
        });
    const responses = Object.entries(method.responses).reduce((all, [status, response]) => {
        const schema = response.schema || response.content?.['application/json']?.schema;
        return {
            ...all,
            [status]: {
                validate: schema ? validator.json(schema) : validator.empty()
            }
        };
    }, {});
    const expected = (pathName.match(/[^/]+/g) || []).map(s => s.toString());
    return {
        request: async function validateRequest({
            query = {},
            body = {},
            files = {},
            pathParameters = {},
            headers = {},
            path = ''
        }) {
            const errors = [];
            Iif (params.length === 0) {
                const { error } = await validator.empty()(body);
                if (error) {
                    error.where = 'body';
                    errors.push(error);
                }
                Object.keys(query).forEach(name => {
                    errors.push({
                        where: 'query',
                        name,
                        actual: query[name],
                        expected: undefined
                    });
                });
            } else {
                let hasBody = false;
                for (let i = 0; i < params.length; i += 1) {
                    let value;
                    const param = params[i];
                    let validate = param.validate;
                    switch (param.in) {
                        case 'header':
                            value = headers[param.name];
                            break;
                        case 'query':
                            value = query[param.name];
                            validate = async value => {
                                const validation = await param.validate(value);
                                // reassign value if casted. E.g. 'true' -> true or '1' -> 1
                                if (validation.result !== value) query[param.name] = validation.result;
                                return validation;
                            };
                            break;
                        case 'path':
                            if (path) {
                                const actual = path.substring(basePath.length).match(/[^/]+/g);
                                value = actual ? actual[expected.indexOf(`{${param.name}}`)] : undefined;
                            } else {
                                value = pathParameters[param.name];
                                validate = async value => {
                                    const validation = await param.validate(value);
                                    // reassign value if casted. E.g. 'true' -> true or '1' -> 1
                                    if (validation.result !== value) pathParameters[param.name] = validation.result;
                                    return validation;
                                };
                            }
                            break;
                        case 'formData':
                            value = param.type === 'file' ? files[param.name] : body[param.name];
                            hasBody = true;
                            break;
                        case 'body':
                            value = body;
                            hasBody = true;
                            break;
                    }
                    const { error } = await validate(value);
                    if (error) {
                        error.where = param.in;
                        error.name = param.name;
                        errors.push(error);
                    }
                }
                Iif (!hasBody) {
                    const { error } = await validator.empty()(body);
                    error && errors.push(error);
                }
            }
            return errors;
        },
        response: async function validateResponse({status, body}) {
            const { validate } = responses[status] || responses.default;
            const { error } = await validate(body);
            return error ? [error] : [];
        }
    };
}
 
module.exports = (swaggerDocument, pathName, methodName, basePath) => {
    if (pathName && methodName) return methodValidator(swaggerDocument, pathName, methodName, basePath);
    return (async() => {
        const swagger = await swaggerParser.dereference(swaggerDocument);
        return Object.entries(swagger.paths).reduce(
            (validators, [pathName, path]) => {
                Eif (!pathName.startsWith('x-')) {
                    Object.entries(path).forEach(([methodName, method]) => {
                        Eif (methodName !== 'parameters' && !methodName.startsWith('x-')) {
                            let basePath = swagger.swagger && swagger.basePath;
                            Iif (swagger.openapi) {
                                const docUrl = swagger.servers?.[0]?.url;
                                const schemaUrl = method.servers?.[0]?.url;
                                basePath = schemaUrl
                                    ? schemaUrl.startsWith('/') && schemaUrl
                                    : docUrl?.startsWith('/') && docUrl;
                            }
                            Eif (!basePath) basePath = '';
                            validators[method.operationId] = methodValidator(
                                swagger,
                                basePath + pathName,
                                methodName,
                                basePath
                            );
                        }
                    });
                }
                return validators;
            },
            {}
        );
    })();
};