/
betfair_encoder.js
107 lines (95 loc) · 3.21 KB
/
betfair_encoder.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
//(C) 2012 Anton Zemlyanov
//The module "encodes" native JavaScript objects into SOAP xml invocation requests
//see Sports API documentation on http://bdp.betfair.com
//Exported properties:
//encode - converts native JavaScript object into Betfair SOAP XML request
var DomJS = require('dom-js').DomJS;
var Element = require('dom-js').Element;
var Text = require('dom-js').Text;
// var xmljs = require('libxmljs');
var util = require('util');
exports.encode = function(action, schema, input) {
// Envelope tag
var root = new Element('soap:Envelope', {
'xmlns:soap' : 'http://schemas.xmlsoap.org/soap/envelope/',
'xmlns:xsi' : 'http://www.w3.org/2001/XMLSchema-instance',
'xmlns:xsd' : 'http://www.w3.org/'
});
// Body tag
var body = new Element('soap:Body');
root.children.push(body);
// action tag
var act = new Element(action, {
xmlns : schema
});
body.children.push(act);
// request tag
var request = new Element("request");
act.children.push(request);
// incode input
encodeObject(input, request);
// serialize document to XML
// var domjs = new DomJS();
var text = root.toXml();
console.log("text", text);
return text;
}
function encodeObject(object, parent) {
for ( var itemKey in object) {
var itemVal = object[itemKey];
//console.log(itemKey + "===" + itemVal);
//console.log(itemVal);
switch (typeof itemVal) {
case 'string':
var strElement = new Element(itemKey, {}, [ new Text(itemVal) ]);
parent.children.push(strElement);
break;
case 'number':
var strElement = new Element(itemKey, {}, [ new Text(itemVal
.toString()) ]);
parent.children.push(strElement);
break;
case 'object':
if (util.isArray(itemVal)) {
// encode array
var arrElement = new Element(itemKey);
arrElement.children.push(encodeArray(itemVal, arrElement));
parent.children.push(arrElement);
} else {
// encode object
var objElement = new Element(itemKey);
arrElement.children.push(encodeObject(itemVal, objElement));
parent.children.push(objElement);
}
default:
// console.log("unknown");
break;
}
}
return;
}
function encodeArray(array, parent) {
// console.log("array", array);
var itemTagName = array.shift();
for ( var itemKey in array) {
var itemVal = array[itemKey];
console.log("encodeArray: itemVal", itemVal);
switch (typeof itemVal) {
case 'string':
console.log("string");
var strElement = new Element(itemKey, {}, [ new Text(itemVal) ]);
parent.children.push(strElement);
break;
case 'number':
console.log("number");
var strElement = new Element(itemKey, {}, [ new Text(itemVal
.toString()) ]);
parent.children.push(strElement);
break;
default:
// console.log("unknown");
break;
}
}
return;
}