forked from yui/nodejs-yui3
/
io.js
105 lines (88 loc) · 4.04 KB
/
io.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
/**
* A NodeJS transport for IO
* @module io-nodejs
*/
YUI.add('io-nodejs', function(Y) {
var url = YUI.require('url'),
http = YUI.require('http');
var NodeTransport = {
id: 'nodejs',
src: {
send: function(uri, transactionObject, config) {
//Y.log(sys.inspect(transactionObject), 'info', 'nodeio');
//Y.log(sys.inspect(config), 'info', 'nodeio');
Y.io.xdrResponse(transactionObject, config, 'start');
var urlInfo = url.parse(uri, parseQueryString=false);
if (!config.headers) {
config.headers = {};
}
config.headers.host = urlInfo.hostname;
if (config.data && config.method === 'POST') {
config.headers['Content-Length'] = config.data.length;
config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers);
}
var host = http.createClient(YUI.urlInfoPort(urlInfo), urlInfo.hostname);
var req_url = urlInfo.pathname;
if (urlInfo.search) {
req_url += urlInfo.search;
}
Y.log('Requesting (' + config.method + '): ' + urlInfo.hostname, 'info', 'nodeio');
Y.log('URL: ' + req_url, 'info', 'nodeio');
var request = host.request(config.method, req_url, config.headers);
request.addListener('response', function (response) {
//sys.puts("STATUS: " + response.statusCode);
//sys.puts("HEADERS: " + JSON.stringify(response.headers));
//response.setBodyEncoding("utf8");
var body = '';
response.addListener('data', function (chunk) {
//sys.puts('chunk: ' + chunk);
body += chunk;
});
response.addListener("end", function() {
var statusText, good, status = response.statusCode;
if (status >= 200 && status < 300) {
statusText = 'OK';
good = true;
} else {
statusText = 'Server Error';
good = false;
}
transactionObject.c = {
status: response.statusCode,
statusText: statusText,
responseText: body,
headers: response.headers,
getAllResponseHeaders: function() {
return this.headers;
},
getResponseHeader: function(h) {
return this.headers[h];
}
}
//sys.print(sys.inspect(transactionObject.c));
Y.io.xdrResponse(transactionObject, config, 'complete');
Y.io.xdrResponse(transactionObject, config, ((good) ? 'success' : 'failure'));
//TODO
//Y.io.xdrResponse(transactionObject, configurationObject, 'timeout');
});
});
if (config.method === 'POST') {
request.write(config.data);
}
if (request.end) {
request.end();
} else {
request.close();
}
},
abort: function() {
//TODO
},
isInProgress: function() {
//TODO
return false;
}
}
};
Y.io.transport(NodeTransport);
}, 'NODE', { requires: ['io', 'io-xdr'], after: ['io-xdr'] });