forked from OptimalBits/node_acl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
contract.js
123 lines (105 loc) · 2.31 KB
/
contract.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
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
/**
Design by Contract module (c) OptimalBits 2011.
Roadmap:
- Optional parameters. ['(string)', 'array']
- Variable number of parameters.['number','...']
api?:
contract(arguments)
.params('string', 'array', '...')
.params('number')
.end()
*/
"use strict";
var noop = {};
var util = require('util');
var _ = require('lodash');
noop.params = function(){
return this;
};
noop.end = function(){};
var contract = function(args){
if(contract.debug===true){
contract.fulfilled = false;
contract.args = _.toArray(args);
contract.checkedParams = [];
return contract;
}else{
return noop;
}
};
contract.params = function(){
var i, len;
this.fulfilled |= checkParams(this.args, _.toArray(arguments));
if(this.fulfilled){
return noop;
}else{
this.checkedParams.push(arguments);
return this;
}
}
contract.end = function(){
if(!this.fulfilled){
printParamsError(this.args, this.checkedParams);
throw new Error('Broke parameter contract');
}
}
var typeOf = function(obj){
return Array.isArray(obj) ? 'array':typeof obj;
};
var checkParams = function(args, contract){
var fulfilled, types, type, i, j;
if(args.length !== contract.length){
return false;
}else{
for(i=0; i<args.length; i++){
try{
types = contract[i].split('|');
}catch(e){
console.log(e, args)
}
if (args[i]) {
type = typeOf(args[i]);
fulfilled = false;
for(j=0; j<types.length; j++){
if (type === types[j]){
fulfilled = true;
break;
}
}
}
if(fulfilled===false){
return false;
}
}
return true;
}
};
var printParamsError = function(args, checkedParams){
var msg = 'Parameter mismatch.\nInput:\n( ',
type,
input,
i;
_.each(args, function(input, key){
type = typeOf(input);
if(key != 0){
msg += ', '
}
msg += input + ': '+type;
})
msg += ')\nAccepted:\n';
for (i=0; i<checkedParams.length;i++){
msg += '('+ argsToString(checkedParams[i]) + ')\n';
}
console.log(msg);
};
var argsToString = function(args){
var res = "";
_.each(args, function(arg, key){
if(key != 0){
res += ', ';
}
res += arg;
})
return res;
}
exports = module.exports = contract;