-
Notifications
You must be signed in to change notification settings - Fork 6
/
assert.js
50 lines (44 loc) · 1.27 KB
/
assert.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
var nodash = require('@smallwins/nodash')
var isPlainObject = nodash.isPlainObject
var isObject = nodash.isObject
var isError = nodash.isError
var has = nodash.has
var invalidType = require('./_invalid-type')
function caps(str) {
var working = (typeof str).slice('')
var first = working[0].toUpperCase()
var rest = working.slice(1, working.length)
return `${first}${rest}`
}
function cleans(str) {
var exp = /function (\w+)\(\) { \[native code\] }/
if (exp.test(str)) {
return str.toString().match(exp)[1]
}
else {
return str
}
}
module.exports = function assert(params, schema) {
if (!isObject(params)) {
throw TypeError('params not an object')
}
if (!isPlainObject(schema)) {
throw TypeError('schema not a plain object')
}
// check for existance of things
Object.keys(schema).forEach(key=> {
if (!has(params, key)) {
throw ReferenceError('missing required params.' + key)
}
// if we made it here the key exists
// check its correctly typed or throw
if (isError(invalidType(key, params, schema))) {
var msg = ''
msg += 'expected ' + cleans(schema[key]) + ' '
msg += 'but received ' + caps(params[key]) + ' "'+ params[key] + '" '
msg += 'for params.' + key
throw TypeError(msg)
}
})
}