aboutsummaryrefslogtreecommitdiff
path: root/src/lib/data-validator.js
blob: 74827c12a641c4c40cf605c11fc74a98ac2c4701 (plain)
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
const {isInteger, isObject} = require('lodash')
const {getLogger} = require('./logger')

const typeNames = {
    'i': 'integer',
    'n': 'number',
    's': 'string',
    'o': 'object',
    'a': 'array',
}

const logger = getLogger('data-validator')


/**************************************/
/**        Common Functions          **/
/**************************************/

/**
 * @param {string} expectedType
 * @param value
 */
function checkType(expectedType, value) {
    switch (expectedType) {
        case 'i':
            return isInteger(value)
        case 'n':
            return typeof value === 'number'
        case 's':
            return typeof value === 'string'
        case 'o':
            return typeof value === 'object'
        case 'a':
            return Array.isArray(value)
        default:
            logger.error(`checkType: unknown type ${expectedType}`)
            return false
    }
}

/**
 * @param {object} data
 * @param {array} schema
 * @throws Error
 */
function validateObjectSchema(data, schema) {
    if (!isObject(data))
        throw new Error(`data is not an object`)

    for (const field of schema) {
        let [name, types, required] = field
        if (!(name in data)) {
            if (required)
                throw new Error(`missing required field ${name}`)

            continue
        }

        types = types.split('')

        if (!types
            .map(type => checkType(type, data[name]))
            .some(result => result === true)) {

            let error = `'${name}' must be `
            if (types.length === 1) {
                error += typeNames[types[0]]
            } else {
                error += 'any of: ' + types.map(t => typeNames[t]).join(', ')
            }

            throw new Error(error)
        }
    }
}


/********************************************/
/**      Request input data validators      */
/********************************************/

function validateInputTargetsListFormat(targets) {
    if (!Array.isArray(targets))
        throw new Error('targets must be array')

    if (!targets.length)
        throw new Error('targets are empty')

    for (const t of targets) {
        const type = typeof t
        if (type !== 'string')
            throw new Error(`all targets must be strings, ${type} given`)
    }
}

function validateInputTargetAndConcurrency(data, onlyTarget = false) {
    const schema = [
        ['target',      's',     true],
    ]

    if (!onlyTarget) {
        schema.push(
            ['concurrency', 'i', true]
        )
    }

    validateObjectSchema(data, schema)

    if (!onlyTarget && data.concurrency <= 0)
        throw new Error('Invalid concurrency value.')
}

/**
 * @param data
 * @param {Worker|null} worker
 * @return {null|string[]}
 */
function validateInputTargets(data, worker) {
    // null means all targets
    let targets = null

    if (data.targets !== undefined) {
        targets = data.targets

        validateInputTargetsListFormat(targets)

        if (worker !== null) {
            for (const t of targets) {
                if (!worker.hasTarget(t))
                    throw new Error(`invalid target '${t}'`)
            }
        }
    }

    return targets
}

module.exports = {
    validateObjectSchema,
    validateInputTargetsListFormat,
    validateInputTargetAndConcurrency,
    validateInputTargets,
}