-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (78 loc) · 1.82 KB
/
index.js
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
/**
* Dependencies.
*/
const protocol = require('protocol-buffers-schema').parse
/**
* Create schema from protocol buffer file.
*
* Examples:
*
* const validate = schema(`
* message User {
* required string email = 1;
* }
* `)
*
* valiate('User', {
* email: '[email protected]'
* })
*
* @param {String} schema
* @return {Function}
* @api public
*/
module.exports = function (schema, validator, mixins) {
const obj = messages(schema, mixins)
return (name, arg) => {
const result = {}
const message = obj[name]
Object.keys(message)
.map(key => {
const validate = validator && validator[key]
const value = message[key](arg[key])
if (validate && !validate(value)) throw new Error(`field ${key} is malformatted`)
if (value) result[key] = value
})
return result
}
}
/**
* Parse messages from schema txt.
*
* @param {String} schema
* @param {Object} mixins
* @return {Object}
* @api private
*/
function messages (schema, mixins) {
const result = {}
const obj = protocol(schema)
obj.messages.map(message => {
result[message.name] = fields(message.fields, mixins)
})
return result
}
/**
* Parse fields from schema messages.
*
* @param {Array} arr
* @param {Object} mixins
* @return {Object}
* @api private
*/
function fields (arr, mixins) {
const result = {}
arr.map(item => {
const field = item.name
const mixin = item.options.mixin
const type = item.type
result[field] = function (value) {
if (item.required && value == null) throw new ReferenceError(`field ${field} is not defined`)
if (value && typeof value !== type) throw new TypeError(`field ${field} is not a ${type}`)
return mixins && mixin && mixins[mixin]
? mixins[mixin](value)
: value
}
})
return result
}