diff --git a/README.md b/README.md index a98b844..79595aa 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,25 @@ -Restler +Restler [![NPM Version](https://img.shields.io/npm/v/restler.svg?style=flat)](https://www.npmjs.com/package/restler) ![Node Version](https://img.shields.io/node/v/restler.svg?style=flat) ![Downloads](https://img.shields.io/npm/dm/restler.svg?style=flat) ======= (C) Dan Webb (dan@danwebb.net/@danwrong) 2011, Licensed under the MIT-LICENSE -An HTTP client library for node.js (0.6.x and up). Hides most of the complexity of creating and using http.Client. +An HTTP client library for node.js. Hides most of the complexity of creating and using http.Client. -**Release 2.x.x** is dedicated to modifying how errors are handled and emitted. Currently errors are being fired as an on 'error' event but as [@ctavan](https://github.com/ctavan) pointed out on [issue #36](https://github.com/danwrong/restler/pull/36) a better approach (and more commonly in vogue now) would be to pass the error obj to the callback. +See [Version History](https://github.com/danwrong/restler/wiki/Version-History) for changes -Ths change will inevitably affect those using older < 0.2.x versions of restler. Those not ready to upgrade yet are encouraged to stay on the 0.2.x version. +Installing +---------- -See [Version History](https://github.com/danwrong/restler/wiki/Version-History) for changes +``` +npm install restler +``` + +Running the tests +----------------- + +``` +npm test +``` Features @@ -18,15 +28,15 @@ Features * Easy interface for common operations via http.request * Automatic serialization of post data * Automatic serialization of query string data -* Automatic deserialization of XML, JSON and YAML responses to JavaScript objects (if you have js-yaml and/or xml2js in the require path) +* Automatic deserialization of XML, JSON and YAML responses to JavaScript objects * Provide your own deserialization functions for other datatypes * Automatic following of redirects * Send files with multipart requests * Transparently handle SSL (just specify https in the URL) * Deals with basic auth for you, just provide username and password options * Simple service wrapper that allows you to easily put together REST API libraries -* Transparently handle content-encoded responses (gzip, deflate) (requires node 0.6+) -* Transparently handle different content charsets via [iconv](https://github.com/bnoordhuis/node-iconv) (if available) +* Transparently handle content-encoded responses (gzip, deflate) +* Transparently handle different content charsets via [iconv-lite](https://github.com/ashtuchkin/iconv-lite) API @@ -43,6 +53,7 @@ Basic method to make a request of any type. The function returns a RestRequest o * `fail: function(data, response)` - emitted when the request was successful, but 4xx status code returned. Gets passed the response data and the response object as arguments. * `error: function(err, response)` - emitted when some errors have occurred (eg. connection aborted, parse, encoding, decoding failed or some other unhandled errors). Gets passed the `Error` object and the response object (when available) as arguments. * `abort: function()` - emitted when `request.abort()` is called. +* `timeout: function(ms)` - when a request takes more than the timeout option eg: {timeout:5000}, the request will be aborted. error and abort events will not be called, instead timeout will be emitted. * `2XX`, `3XX`, `4XX`, `5XX: function(data, response)` - emitted for all requests with response codes in the range (eg. `2XX` emitted for 200, 201, 203). * actual response code: function(data, response) - emitted for every single response code (eg. 404, 201, etc). @@ -73,6 +84,10 @@ Create a DELETE request. Create a HEAD request. +### patch(url, options) + +Create a PATCH request. + ### json(url, data, options) Send json `data` via GET method. @@ -81,6 +96,9 @@ Send json `data` via GET method. Send json `data` via POST method. +### putJson(url, data, options) + +Send json `data` via PUT method. ### Parsers @@ -98,7 +116,7 @@ All of these attempt to turn the response into a JavaScript object. In order to ### Options -* `method` Request method, can be get, post, put, del. Defaults to `"get"`. +* `method` Request method, can be get, post, put, delete. Defaults to `"get"`. * `query` Query string variables as a javascript object, will override the querystring in the URL. Defaults to empty. * `data` The data to be added to the body of the request. Can be a string or any object. Note that if you want your request body to be JSON with the `Content-Type: application/json`, you need to @@ -106,37 +124,45 @@ Note that if you want your request body to be JSON with the `Content-Type: appli Also you can use `json()` and `postJson()` methods. * `parser` A function that will be called on the returned data. Use any of predefined `restler.parsers`. See parsers section below. Defaults to `restler.parsers.auto`. * `encoding` The encoding of the request body. Defaults to `"utf8"`. -* `decoding` The encoding of the response body. For a list of supported values see [Buffers](http://nodejs.org/docs/latest/api/buffers.html#buffers). Additionally accepts `"buffer"` - returns response as `Buffer`. Defaults to `"utf8"`. +* `decoding` The encoding of the response body. For a list of supported values see [Buffers](http://nodejs.org/api/buffer.html#buffer_buffer). Additionally accepts `"buffer"` - returns response as `Buffer`. Defaults to `"utf8"`. * `headers` A hash of HTTP headers to be sent. Defaults to `{ 'Accept': '*/*', 'User-Agent': 'Restler for node.js' }`. * `username` Basic auth username. Defaults to empty. * `password` Basic auth password. Defaults to empty. +* `accessToken` OAuth Bearer Token. Defaults to empty. * `multipart` If set the data passed will be formated as `multipart/form-encoded`. See multipart example below. Defaults to `false`. * `client` A http.Client instance if you want to reuse or implement some kind of connection pooling. Defaults to empty. * `followRedirects` If set will recursively follow redirects. Defaults to `true`. +* `timeout` If set, will emit the timeout event when the response does not return within the said value (in ms) +* `rejectUnauthorized` If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default true. Example usage ------------- ```javascript -var sys = require('util'), - rest = require('./restler'); +var rest = require('./restler'); rest.get('http://google.com').on('complete', function(result) { if (result instanceof Error) { - sys.puts('Error: ' + result.message); + console.log('Error:', result.message); this.retry(5000); // try again after 5 sec } else { - sys.puts(result); + console.log(result); } }); rest.get('http://twaud.io/api/v1/users/danwrong.json').on('complete', function(data) { - sys.puts(data[0].message); // auto convert to object + console.log(data[0].message); // auto convert to object }); rest.get('http://twaud.io/api/v1/users/danwrong.xml').on('complete', function(data) { - sys.puts(data[0].sounds[0].sound[0].message); // auto convert to object + console.log(data[0].sounds[0].sound[0].message); // auto convert to object +}); + +rest.get('http://someslowdomain.com',{timeout: 10000}).on('timeout', function(ms){ + console.log('did not return within '+ms+' ms'); +}).on('complete',function(data,response){ + console.log('did not time out'); }); rest.post('http://user:pass@service.com/action', { @@ -157,7 +183,7 @@ rest.post('https://twaud.io/api/v1/upload.json', { 'sound[file]': rest.file('doug-e-fresh_the-show.mp3', null, 321567, null, 'audio/mpeg') } }).on('complete', function(data) { - sys.puts(data.audio_url); + console.log(data.audio_url); }); // create a service constructor for very easy API wrappers a la HTTParty... @@ -174,7 +200,7 @@ Twitter = rest.service(function(u, p) { var client = new Twitter('danwrong', 'password'); client.update('Tweeting using a Restler service thingy').on('complete', function(data) { - sys.p(data); + console.log(data); }); // post JSON @@ -183,26 +209,12 @@ rest.postJson('http://example.com/action', jsonData).on('complete', function(dat // handle response }); -``` - -Running the tests ------------------ -install **[nodeunit](https://github.com/caolan/nodeunit)** - -```bash -npm install nodeunit -``` - -then - -```bash -node test/all.js -``` - -or +// put JSON +var jsonData = { id: 334 }; +rest.putJson('http://example.com/action', jsonData).on('complete', function(data, response) { + // handle response +}); -```bash -nodeunit test/restler.js ``` TODO diff --git a/lib/multipartform.js b/lib/multipartform.js index e917676..7196724 100644 --- a/lib/multipartform.js +++ b/lib/multipartform.js @@ -67,8 +67,9 @@ Part.prototype = { if (this.value.data) { header = "Content-Disposition: form-data; name=\"" + this.name + "\"; filename=\"" + this.value.filename + "\"\r\n" + + "Content-Length: " + this.value.data.length + "\r\n" + "Content-Type: " + this.value.contentType; - } if (this.value instanceof File) { + } else if (this.value instanceof File) { header = "Content-Disposition: form-data; name=\"" + this.name + "\"; filename=\"" + this.value.filename + "\"\r\n" + "Content-Length: " + this.value.fileSize + "\r\n" + @@ -127,6 +128,10 @@ Part.prototype = { }); })(); // reader() }); + } else if (this.value instanceof Data) { + stream.write(this.value.data); + stream.write("\r\n"); + callback(); } else { stream.write(this.value + "\r\n"); callback(); diff --git a/lib/restler.js b/lib/restler.js index 83a68a4..8a378b0 100644 --- a/lib/restler.js +++ b/lib/restler.js @@ -1,30 +1,24 @@ -var sys = require('util'); -var http = require('http'); -var https = require('https'); -var url = require('url'); -var qs = require('querystring'); -var multipart = require('./multipartform'); -var zlib = null; -var Iconv = null; - -try { - zlib = require('zlib'); -} catch (err) {} - -try { - Iconv = require('iconv').Iconv; -} catch (err) {} +var util = require('util'), + events = require("events"), + http = require('http'), + https = require('https'), + url = require('url'), + qs = require('qs'), + multipart = require('./multipartform'), + zlib = require('zlib'), + iconv = require('iconv-lite'); function mixin(target, source) { source = source || {}; Object.keys(source).forEach(function(key) { target[key] = source[key]; }); - + return target; } function Request(uri, options) { + events.EventEmitter.call(this); this.url = url.parse(uri); this.options = options; this.headers = { @@ -33,26 +27,24 @@ function Request(uri, options) { 'Host': this.url.host }; - if (zlib) { - this.headers['Accept-Encoding'] = 'gzip, deflate'; - } - + this.headers['Accept-Encoding'] = 'gzip, deflate'; + mixin(this.headers, options.headers || {}); - + // set port and method defaults if (!this.url.port) this.url.port = (this.url.protocol == 'https:') ? '443' : '80'; if (!this.options.method) this.options.method = (this.options.data) ? 'POST' : 'GET'; if (typeof this.options.followRedirects == 'undefined') this.options.followRedirects = true; - + // stringify query given in options of not given in URL if (this.options.query && !this.url.query) { - if (typeof this.options.query == 'object') + if (typeof this.options.query == 'object') this.url.query = qs.stringify(this.options.query); else this.url.query = this.options.query; } - - this._applyBasicAuth(); - + + this._applyAuth(); + if (this.options.multipart) { this.headers['Content-Type'] = 'multipart/form-data; boundary=' + multipart.defaultBoundary; var multipart_size = multipart.sizeOf(this.options.data, multipart.defaultBoundary); @@ -76,26 +68,30 @@ function Request(uri, options) { this.headers['Content-Length'] = buffer.length; } } + if (!this.options.data) { + this.headers['Content-Length'] = 0; + } } - + var proto = (this.url.protocol == 'https:') ? https : http; - + this.request = proto.request({ host: this.url.hostname, port: this.url.port, path: this._fullPath(), method: this.options.method, - headers: this.headers + headers: this.headers, + rejectUnauthorized: this.options.rejectUnauthorized }); - + this._makeRequest(); } -Request.prototype = new process.EventEmitter(); +util.inherits(Request, events.EventEmitter); mixin(Request.prototype, { _isRedirect: function(response) { - return ([301, 302, 303].indexOf(response.statusCode) >= 0); + return ([301, 302, 303, 307].indexOf(response.statusCode) >= 0); }, _fullPath: function() { var path = this.url.pathname || '/'; @@ -103,23 +99,25 @@ mixin(Request.prototype, { if (this.url.query) path += '?' + this.url.query; return path; }, - _applyBasicAuth: function() { + _applyAuth: function() { var authParts; - + if (this.url.auth) { authParts = this.url.auth.split(':'); this.options.username = authParts[0]; this.options.password = authParts[1]; } - - if (this.options.username && this.options.password) { + + if (this.options.username && this.options.password !== undefined) { var b = new Buffer([this.options.username, this.options.password].join(':')); this.headers['Authorization'] = "Basic " + b.toString('base64'); + } else if (this.options.accessToken) { + this.headers['Authorization'] = "Bearer " + this.options.accessToken; } }, _responseHandler: function(response) { var self = this; - + if (self._isRedirect(response) && self.options.followRedirects) { try { // 303 should redirect and retrieve content with the GET method @@ -141,13 +139,13 @@ mixin(Request.prototype, { } } else { var body = ''; - + response.setEncoding('binary'); - + response.on('data', function(chunk) { body += chunk; }); - + response.on('end', function() { response.rawEncoded = body; self._decode(new Buffer(body, 'binary'), response, function(err, body) { @@ -177,18 +175,15 @@ mixin(Request.prototype, { } }, _iconv: function(body, response) { - if (Iconv) { - var charset = response.headers['content-type']; + var charset = response.headers['content-type']; + if (charset) { + charset = /\bcharset=(.+)(?:;|$)/i.exec(charset); if (charset) { - charset = /\bcharset=(.+)(?:;|$)/i.exec(charset); - if (charset) { - charset = charset[1].trim().toUpperCase(); - if (charset != 'UTF-8') { - try { - var iconv = new Iconv(charset, 'UTF-8//TRANSLIT//IGNORE'); - return iconv.convert(body); - } catch (err) {} - } + charset = charset[1].trim().toUpperCase(); + if (charset != 'UTF-8') { + try { + return iconv.decode(body, charset); + } catch (err) {} } } } @@ -208,9 +203,22 @@ mixin(Request.prototype, { } }, _fireError: function(err, response) { + this._fireCancelTimeout(); this.emit('error', err, response); this.emit('complete', err, response); }, + _fireCancelTimeout: function(){ + var self = this; + if(self.options.timeout){ + clearTimeout(self.options.timeoutFn); + } + }, + _fireTimeout: function(err){ + this.emit('timeout', err); + this.aborted = true; + this.timedout = true; + this.request.abort(); + }, _fireSuccess: function(body, response) { if (parseInt(response.statusCode) >= 400) { this.emit('fail', body, response); @@ -223,10 +231,18 @@ mixin(Request.prototype, { }, _makeRequest: function() { var self = this; + var timeoutMs = self.options.timeout; + if(timeoutMs){ + self.options.timeoutFn = setTimeout(function(){ + self._fireTimeout(timeoutMs); + },timeoutMs); + } this.request.on('response', function(response) { + self._fireCancelTimeout(); self.emit('response', response); self._responseHandler(response); }).on('error', function(err) { + self._fireCancelTimeout(); if (!self.aborted) { self._fireError(err, null); } @@ -248,11 +264,11 @@ mixin(Request.prototype, { }); } else { if (this.data) { - this.request.write(this.data.toString(), this.options.encoding || 'utf8'); + this.request.write(this.data, this.options.encoding || 'utf8'); } this.request.end(); } - + return this; }, abort: function(err) { @@ -301,12 +317,12 @@ function shortcutOptions(options, method) { options.parser = (typeof options.parser !== "undefined") ? options.parser : parsers.auto; return options; } - -function request(url, options) { + +function request(url, options) { var request = new Request(url, options); request.on('error', function() {}); process.nextTick(request.run.bind(request)); - return request; + return request; } function get(url, options) { @@ -347,6 +363,10 @@ function postJson(url, data, options) { return json(url, data, options, 'POST'); } +function putJson(url, data, options) { + return json(url, data, options, 'PUT'); +} + var parsers = { auto: function(data, callback) { var contentType = this.headers['content-type']; @@ -380,12 +400,16 @@ var parsers = { }, json: function(data, callback) { if (data && data.length) { + var parsedData; try { - callback(null, JSON.parse(data)); + parsedData = JSON.parse(data); } catch (err) { err.message = 'Failed to parse JSON body: ' + err.message; callback(err, null); } + if (parsedData !== undefined) { + callback(null, parsedData); + } } else { callback(null, null); } @@ -398,7 +422,7 @@ parsers.auto.matchers = { try { var yaml = require('yaml'); - + parsers.yaml = function(data, callback) { if (data) { try { @@ -411,7 +435,7 @@ try { callback(null, null); } }; - + parsers.auto.matchers['application/yaml'] = parsers.yaml; } catch(e) {} @@ -431,7 +455,7 @@ try { callback(null, null); } }; - + parsers.auto.matchers['application/xml'] = parsers.xml; } catch(e) { } @@ -448,9 +472,9 @@ var decoders = { function Service(defaults) { if (defaults.baseURL) { this.baseURL = defaults.baseURL; - delete defaults.baseURL; + delete defaults.baseURL; } - + this.defaults = defaults; } @@ -505,6 +529,7 @@ mixin(exports, { head: head, json: json, postJson: postJson, + putJson: putJson, parsers: parsers, file: multipart.file, data: multipart.data diff --git a/package.json b/package.json index 3fe5d78..83143d7 100644 --- a/package.json +++ b/package.json @@ -1,18 +1,39 @@ { - "name": "restler", - "version": "2.0.2", - "description": "An HTTP client library for node.js", - "contributors": [{ "name": "Dan Webb", "email": "dan@danwebb.net" }], - "homepage": "https://github.com/danwrong/restler", - "directories" : { "lib" : "./lib" }, - "main" : "./lib/restler", - "engines": { "node": ">= 0.6.x" }, - "dependencies": { + "name": "restler", + "version": "3.2.2", + "description": "An HTTP client library for node.js", + "contributors": [ + { + "name": "Dan Webb", + "email": "dan@danwebb.net" }, - "devDependencies": { - "nodeunit": ">=0.5.0", - "xml2js" : ">=0.1.0", - "yaml" : ">=0.2.0", - "iconv": ">=1.0.0" + { + "name": "Ben Marvell", + "email": "ben@marvell-consulting.com" } + ], + "homepage": "https://github.com/danwrong/restler", + "repository": { + "type": "git", + "url": "https://github.com/danwrong/restler.git" + }, + "directories": { + "lib": "./lib" + }, + "main": "./lib/restler", + "engines": { + "node": ">= 0.10.x" + }, + "scripts": { + "test": "node test/all.js" + }, + "dependencies": { + "qs": "1.2.0", + "xml2js": "0.4.0", + "yaml": "0.2.3", + "iconv-lite": "0.2.11" + }, + "devDependencies": { + "nodeunit": "0.8.2" + } } diff --git a/test/restler.js b/test/restler.js index 77e531b..ec7d926 100644 --- a/test/restler.js +++ b/test/restler.js @@ -1,22 +1,9 @@ - -var rest = require('../lib/restler'); -var http = require('http'); -var sys = require('util'); -var path = require('path'); -var fs = require('fs'); -var crypto = require('crypto'); -var zlib = null; -var Iconv = null; - -try { - zlib = require('zlib'); -} catch (err) {} - -try { - Iconv = require('iconv').Iconv; -} catch (err) {} - -var p = sys.inspect; +var rest = require('../lib/restler'), + http = require('http'), + util = require('util'), + path = require('path'), + fs = require('fs'), + crypto = require('crypto'); var port = 9000; var hostname = 'localhost'; @@ -24,7 +11,9 @@ var host = 'http://' + hostname + ':' + port; var nodeunit = require('nodeunit'); nodeunit.assert.re = function(actual, expected, message) { - new RegExp(expected).test(actual) || nodeunit.assert.fail(actual, expected, message, '~=', nodeunit.assert.re); + if (!new RegExp(expected).test(actual)) { + nodeunit.assert.fail(actual, expected, message, '~=', nodeunit.assert.re); + } }; @@ -37,7 +26,9 @@ function setup(response) { function teardown() { return function (next) { - this.server._handle && this.server.close(); + if (this.server._handle) { + this.server.close(); + } process.nextTick(next); }; } @@ -154,6 +145,13 @@ module.exports['Basic'] = { }); }, + 'Should POST buffer body': function(test) { + rest.post(host, { data: new Buffer('balls') }).on('complete', function(data) { + test.re(data, /\r\n\r\nballs/, 'should have balls in the body'); + test.done(); + }); + }, + 'Should serialize POST body': function(test) { rest.post(host, { data: { q: 'balls' } }).on('complete', function(data) { test.re(data, /content-type\: application\/x-www-form-urlencoded/, 'should set content-type'); @@ -172,6 +170,13 @@ module.exports['Basic'] = { }); }, + 'Should send Bearer auth': function(test) { + rest.post(host, { accessToken: 't0k3n' }).on('complete', function(data) { + test.re(data, /authorization\: Bearer t0k3n/, 'should have "authorization "header'); + test.done(); + }); + }, + 'Should send basic auth': function(test) { rest.post(host, { username: 'danwrong', password: 'flange' }).on('complete', function(data) { test.re(data, /authorization\: Basic ZGFud3Jvbmc6Zmxhbmdl/, 'should have "authorization "header'); @@ -179,6 +184,13 @@ module.exports['Basic'] = { }); }, + 'Should send basic auth with blank password': function(test) { + rest.post(host, { username: 'danwrong', password: '' }).on('complete', function(data) { + test.re(data, /authorization\: Basic ZGFud3Jvbmc6/, 'should have "authorization "header'); + test.done(); + }); + }, + 'Should send basic auth if in url': function(test) { rest.post('http://danwrong:flange@' + hostname + ':' + port).on('complete', function(data) { test.re(data, /authorization\: Basic ZGFud3Jvbmc6Zmxhbmdl/, 'should have "authorization" header'); @@ -251,10 +263,12 @@ module.exports['Basic'] = { function command() { var args = [].slice.call(arguments); var method = args.shift(); - method && setTimeout(function() { - request[method](); - command.apply(null, args); - }, 50); + if (method) { + setTimeout(function() { + request[method](); + command.apply(null, args); + }, 50); + } } request = rest.get(host, { headers: { 'x-delay': '1000' } }).on('complete', function() { @@ -280,14 +294,33 @@ module.exports['Multipart'] = { data: { a: 10, b: 'thing' }, multipart: true }).on('complete', function(data) { - test.re(data, /content-type\: multipart\/form-data/, 'should set "content-type" header') + test.re(data, /content-type\: multipart\/form-data/, 'should set "content-type" header'); test.re(data, /name="a"(\s)+10/, 'should send a=10'); test.re(data, /name="b"(\s)+thing/, 'should send b=thing'); test.re(data, /content-length: 200/, 'should send content-length header'); test.done(); }); - } + }, + + 'Test multipart request with Data vars': function(test) { + rest.post(host, { + data: { + a: 10, + b: rest.data('b.txt', 'text/plain', 'thing'), + c: rest.data('c.txt', 'text/plain', new Buffer('thing')) + }, + multipart: true + }).on('complete', function(data) { + test.re(data, /content-type\: multipart\/form-data/, 'should set "content-type" header'); + test.re(data, /name="a"(\s)+10/, 'should send a=10'); + test.re(data, /name="b"; filename="b.txt"\s+Content-Length: 5\s+Content-Type: text\/plain\s+thing\s/, 'should send b=thing'); + test.re(data, /name="c"; filename="c.txt"\s+Content-Length: 5\s+Content-Type: text\/plain\s+thing\s/, 'should send c=thing'); + test.re(data, /content-length: 410/, 'should send content-length header'); + + test.done(); + }); + }, }; @@ -367,6 +400,12 @@ function dataResponse(request, response) { }); response.end(Buffer('e0e1e2e3e4e5b8e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff', 'hex')); break; + case '/timeout': + setTimeout(function() { + response.writeHead(200); + response.end('that took a while'); + }, 100); + break; default: response.writeHead(404); response.end(); @@ -380,87 +419,79 @@ module.exports['Deserialization'] = { 'Should parse JSON': function(test) { rest.get(host + '/json').on('complete', function(data) { - test.equal(data.ok, true, 'returned: ' + p(data)); + test.equal(data.ok, true, 'returned: ' + util.inspect(data)); test.done(); }); }, 'Should parse XML': function(test) { rest.get(host + '/xml').on('complete', function(data, response) { - test.equal(data.ok, 'true', 'returned: ' + response.raw + ' || ' + p(data)); + test.equal(data.document.ok[0], 'true', 'returned: ' + response.raw + ' parsed to ' + util.inspect(data)); test.done(); }); }, 'Should parse YAML': function(test) { rest.get(host + '/yaml').on('complete', function(data) { - test.equal(data.ok, true, 'returned: ' + p(data)); + test.equal(data.ok, true, 'returned: ' + util.inspect(data)); test.done(); }); }, 'Should gunzip': function(test) { - if (zlib) { - rest.get(host + '/gzip').on('complete', function(data) { - test.re(data, /^(compressed data){10}$/, 'returned: ' + p(data)); - test.done(); - }); - } else { + rest.get(host + '/gzip').on('complete', function(data) { + test.re(data, /^(compressed data){10}$/, 'returned: ' + util.inspect(data)); test.done(); - } + }); }, 'Should inflate': function(test) { - if (zlib) { - rest.get(host + '/deflate').on('complete', function(data) { - test.re(data, /^(compressed data){10}$/, 'returned: ' + p(data)); - test.done(); - }) - } else { + rest.get(host + '/deflate').on('complete', function(data) { + test.re(data, /^(compressed data){10}$/, 'returned: ' + util.inspect(data)); test.done(); - } + }); }, 'Should decode and parse': function(test) { - if (zlib) { - rest.get(host + '/truth').on('complete', function(data) { - try { - with (data) { - var result = what + (is + the + answer + to + life + the + universe + and + everything).length; - } - test.equal(result, 42, 'returned: ' + p(data)); - } catch (err) { - test.ok(false, 'returned: ' + p(data)); - } - test.done(); - }) - } else { + rest.get(host + '/truth').on('complete', function(data) { + var expected = { + what: -6, + is: {}, + the: [ 0, 0, 0 ], + answer: 'answer', + to: 2, + life: 'life', + universe: null, + and: 3.14, + everything: true + }; + test.deepEqual(data, expected, 'returned: ' + util.inspect(data)); test.done(); - } + }); }, 'Should decode as buffer': function(test) { rest.get(host + '/binary', { decoding: 'buffer' }).on('complete', function(data) { test.ok(data instanceof Buffer, 'should be buffer'); - test.equal(data.toString('base64'), 'CR5Ah8g=', 'returned: ' + p(data)); + test.equal(data.toString('base64'), 'CR5Ah8g=', 'returned: ' + util.inspect(data)); test.done(); - }) + }); }, 'Should decode as binary': function(test) { rest.get(host + '/binary', { decoding: 'binary' }).on('complete', function(data) { - test.ok(typeof data == 'string', 'should be string: ' + p(data)); - test.equal(data, '\t\u001e@‡È', 'returned: ' + p(data)); + test.ok(typeof data == 'string', 'should be string: ' + util.inspect(data)); + test.equal(data, '\t\u001e@‡È', 'returned: ' + util.inspect(data)); test.done(); - }) + }); }, 'Should decode as base64': function(test) { rest.get(host + '/binary', { decoding: 'base64' }).on('complete', function(data) { - test.ok(typeof data == 'string', 'should be string: ' + p(data)); - test.equal(data, 'CR5Ah8g=', 'returned: ' + p(data)); + test.ok(typeof data == 'string', 'should be string: ' + util.inspect(data)); + test.equal(data, 'CR5Ah8g=', 'returned: ' + util.inspect(data)); test.done(); - }) + }); }, 'Should post and parse JSON': function(test) { @@ -471,15 +502,23 @@ module.exports['Deserialization'] = { }, data: JSON.stringify(obj) }).on('complete', function(data) { - test.equal(obj.secret, data.secret, 'returned: ' + p(data)); + test.equal(obj.secret, data.secret, 'returned: ' + util.inspect(data)); test.done(); - }) + }); }, 'Should post and parse JSON via shortcut method': function(test) { var obj = { secret : 'very secret string' }; rest.postJson(host + '/push-json', obj).on('complete', function(data) { - test.equal(obj.secret, data.secret, 'returned: ' + p(data)); + test.equal(obj.secret, data.secret, 'returned: ' + util.inspect(data)); + test.done(); + }); + }, + + 'Should put and parse JSON via shortcut method': function(test) { + var obj = { secret : 'very secret string' }; + rest.putJson(host + '/push-json', obj).on('complete', function(data) { + test.equal(obj.secret, data.secret, 'returned: ' + util.inspect(data)); test.done(); }); }, @@ -487,15 +526,17 @@ module.exports['Deserialization'] = { 'Should understand custom mime-type': function(test) { rest.parsers.auto.matchers['application/vnd.github+json'] = function(data, callback) { rest.parsers.json.call(this, data, function(err, data) { - err || (data.__parsedBy__ = 'github'); + if (!err) { + data.__parsedBy__ = 'github'; + } callback(err, data); }); }; rest.get(host + '/custom-mime').on('complete', function(data) { test.expect(3); - test.ok(Array.isArray(data), 'should be array, returned: ' + p(data)); - test.equal(data.join(''), '666', 'should be [6,6,6], returned: ' + p(data)); - test.equal(data.__parsedBy__, 'github', 'should use vendor-specific parser, returned: ' + p(data.__parsedBy__)); + test.ok(Array.isArray(data), 'should be array, returned: ' + util.inspect(data)); + test.equal(data.join(''), '666', 'should be [6,6,6], returned: ' + util.inspect(data)); + test.equal(data.__parsedBy__, 'github', 'should use vendor-specific parser, returned: ' + util.inspect(data.__parsedBy__)); test.done(); }); }, @@ -521,11 +562,11 @@ module.exports['Deserialization'] = { 'Should correctly hard-abort request': function(test) { test.expect(4); rest.get(host + '/abort').on('complete', function(data) { - test.ok(data instanceof Error, 'should be error, got: ' + p(data)); + test.ok(data instanceof Error, 'should be error, got: ' + util.inspect(data)); test.equal(this.aborted, true, 'should be aborted'); test.done(); }).on('error', function(err) { - test.ok(err instanceof Error, 'should be error, got: ' + p(err)); + test.ok(err instanceof Error, 'should be error, got: ' + util.inspect(err)); }).on('abort', function(err) { test.equal(this.aborted, true, 'should be aborted'); }).on('success', function() { @@ -538,12 +579,12 @@ module.exports['Deserialization'] = { 'Should correctly handle malformed JSON': function(test) { test.expect(4); rest.get(host + '/mal-json').on('complete', function(data, response) { - test.ok(data instanceof Error, 'should be instanceof Error, got: ' + p(data)); - test.re(data.message, /^Failed to parse/, 'should contain "Failed to parse", got: ' + p(data.message)); - test.equal(response.raw, 'Чебурашка', 'should be "Чебурашка", got: ' + p(response.raw)); + test.ok(data instanceof Error, 'should be instanceof Error, got: ' + util.inspect(data)); + test.re(data.message, /^Failed to parse/, 'should contain "Failed to parse", got: ' + util.inspect(data.message)); + test.equal(response.raw, 'Чебурашка', 'should be "Чебурашка", got: ' + util.inspect(response.raw)); test.done(); }).on('error', function(err) { - test.ok(err instanceof Error, 'should be instanceof Error, got: ' + p(err)); + test.ok(err instanceof Error, 'should be instanceof Error, got: ' + util.inspect(err)); }).on('success', function() { test.ok(false, 'should not have got here'); }).on('fail', function() { @@ -554,12 +595,12 @@ module.exports['Deserialization'] = { 'Should correctly handle malformed XML': function(test) { test.expect(4); rest.get(host + '/mal-xml').on('complete', function(data, response) { - test.ok(data instanceof Error, 'should be instanceof Error, got: ' + p(data)); - test.re(data.message, /^Failed to parse/, 'should contain "Failed to parse", got: ' + p(data.message)); - test.equal(response.raw, 'Чебурашка', 'should be "Чебурашка", got: ' + p(response.raw)); + test.ok(data instanceof Error, 'should be instanceof Error, got: ' + util.inspect(data)); + test.re(data.message, /^Failed to parse/, 'should contain "Failed to parse", got: ' + util.inspect(data.message)); + test.equal(response.raw, 'Чебурашка', 'should be "Чебурашка", got: ' + util.inspect(response.raw)); test.done(); }).on('error', function(err) { - test.ok(err instanceof Error, 'should be instanceof Error, got: ' + p(err)); + test.ok(err instanceof Error, 'should be instanceof Error, got: ' + util.inspect(err)); }).on('success', function() { test.ok(false, 'should not have got here'); }).on('fail', function() { @@ -570,12 +611,12 @@ module.exports['Deserialization'] = { 'Should correctly handle malformed YAML': function(test) { test.expect(4); rest.get(host + '/mal-yaml').on('complete', function(data, response) { - test.ok(data instanceof Error, 'should be instanceof Error, got: ' + p(data)); - test.re(data.message, /^Failed to parse/, 'should contain "Failed to parse", got: ' + p(data.message)); - test.equal(response.raw, '{Чебурашка', 'should be "{Чебурашка", got: ' + p(response.raw)); + test.ok(data instanceof Error, 'should be instanceof Error, got: ' + util.inspect(data)); + test.re(data.message, /^Failed to parse/, 'should contain "Failed to parse", got: ' + util.inspect(data.message)); + test.equal(response.raw, '{Чебурашка', 'should be "{Чебурашка", got: ' + util.inspect(response.raw)); test.done(); }).on('error', function(err) { - test.ok(err instanceof Error, 'should be instanceof Error, got: ' + p(err)); + test.ok(err instanceof Error, 'should be instanceof Error, got: ' + util.inspect(err)); }).on('success', function() { test.ok(false, 'should not have got here'); }).on('fail', function() { @@ -585,14 +626,13 @@ module.exports['Deserialization'] = { }; -if (Iconv) { - module.exports['Deserialization']['Should correctly convert charsets '] = function(test) { - rest.get(host + '/charset').on('complete', function(data) { - test.equal(data, 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'); - test.done(); - }); - }; -} + +module.exports['Deserialization']['Should correctly convert charsets '] = function(test) { + rest.get(host + '/charset').on('complete', function(data) { + test.equal(data, 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'); + test.done(); + }); +}; function redirectResponse(request, response) { @@ -605,8 +645,8 @@ function redirectResponse(request, response) { }); response.end('redirect'); } else { - var count = parseInt(request.url.substr(1)); - var max = parseInt(request.headers['x-redirects']); + var count = parseInt(request.url.substr(1), 10); + var max = parseInt(request.headers['x-redirects'], 10); response.writeHead(count < max ? 301 : 200, { 'location': host + '/' + (count + 1) }); @@ -621,7 +661,7 @@ module.exports['Redirect'] = { 'Should follow redirects': function(test) { rest.get(host).on('complete', function(data) { - test.equal(data, 'redirected', 'returned: ' + p(data)); + test.equal(data, 'redirected', 'returned: ' + util.inspect(data)); test.done(); }); }, @@ -630,7 +670,7 @@ module.exports['Redirect'] = { rest.get(host, { headers: { 'x-redirects': '5' } }).on('complete', function(data) { - test.equal(data, '5', 'returned: ' + p(data)); + test.equal(data, '5', 'returned: ' + util.inspect(data)); test.done(); }); } @@ -669,6 +709,29 @@ module.exports['Content-Length'] = { test.equal(36, data, 'should byte-size content-length'); test.done(); }); + }, + + 'None data request content length': function (test) { + rest.post(host).on('complete', function(data) { + test.equal(0, data, 'should set content-length'); + test.done(); + }); } }; + +module.exports['Timeout'] = { + setUp: setup(dataResponse), + tearDown: teardown(), + + 'will timeout within given time': function(test) { + rest.get(host + '/timeout', {timeout: 50}) + .on('timeout', function () { + test.ok(true, 'timeout endpoint is 100ms and timeout was 50ms'); + test.done(); + }) + .on('complete', function () { + test.ok(false, 'should not emit complete event'); + }); + } +};