1
/* YUI 3.9.1 (build 5852) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
2
YUI.add('io-nodejs', function (Y, NAME) {
4
/*global Y: false, Buffer: false, clearInterval: false, clearTimeout: false, console: false, exports: false, global: false, module: false, process: false, querystring: false, require: false, setInterval: false, setTimeout: false, __filename: false, __dirname: false */
6
* Node.js override for IO, methods are mixed into `Y.IO`
11
* Passthru to the NodeJS <a href="https://github.com/mikeal/request">request</a> module.
12
* This method is return of `require('request')` so you can use it inside NodeJS without
19
// Default Request's cookie jar to `false`. This way cookies will not be
20
// maintained across requests.
21
Y.IO.request = require('request').defaults({jar: false});
24
var codes = require('http').STATUS_CODES;
27
Flatten headers object
31
@param {Object} o The headers object
32
@return {String} The flattened headers object
34
var flatten = function(o) {
36
Object.keys(o).forEach(function(name) {
37
str.push(name + ': ' + o[name]);
39
return str.join('\n');
44
NodeJS IO transport, uses the NodeJS <a href="https://github.com/mikeal/request">request</a>
45
module under the hood to perform all network IO.
46
@method transports.nodejs
49
@return {Object} This object contains only a `send` method that accepts a
50
`transaction object`, `uri` and the `config object`.
53
Y.io('https://somedomain.com/url', {
56
//Extra request module config options.
62
'content-type': 'application/json',
63
body: JSON.stringify({
69
'content_type': 'text/plain'
75
body: 'I am an attachment'
80
success: function(id, e) {
86
Y.IO.transports.nodejs = function() {
88
send: function (transaction, uri, config) {
90
config.notify('start', transaction, config);
91
config.method = config.method || 'GET';
92
config.method = config.method.toUpperCase();
95
method: config.method,
100
if (Y.Lang.isString(config.data)) {
101
rconf.body = config.data;
103
if (rconf.body && rconf.method === 'GET') {
104
rconf.uri += (rconf.uri.indexOf('?') > -1 ? '&' : '?') + rconf.body;
108
if (config.headers) {
109
rconf.headers = config.headers;
111
if (config.timeout) {
112
rconf.timeout = config.timeout;
114
if (config.request) {
115
Y.mix(rconf, config.request);
117
Y.IO.request(rconf, function(err, data) {
121
config.notify(((err.code === 'ETIMEDOUT') ? 'timeout' : 'failure'), transaction, config);
126
status: data.statusCode,
127
statusCode: data.statusCode,
128
statusText: codes[data.statusCode],
129
headers: data.headers,
130
responseText: data.body || '',
132
getResponseHeader: function(name) {
133
return this.headers[name];
135
getAllResponseHeaders: function() {
136
return flatten(this.headers);
141
config.notify('complete', transaction, config);
142
config.notify(((data && (data.statusCode >= 200 && data.statusCode <= 299)) ? 'success' : 'failure'), transaction, config);
153
Y.IO.defaultTransport('nodejs');
157
}, '3.9.1', {"requires": ["io-base"]});