1 | var Q = require('q'),
|
2 | qs = require('qs'),
|
3 | util = require('./util'),
|
4 | EventEmitter = require('tiny-emitter'),
|
5 | async = require('async');
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | function Resource (options) {
|
16 | EventEmitter.call(this, { wildcard: true });
|
17 |
|
18 | options = options || {};
|
19 |
|
20 | this.method = options.method || 'get';
|
21 | this.route = options.route || '';
|
22 | this.middleware = [];
|
23 | this.properties = options.properties || {};
|
24 |
|
25 | return this;
|
26 | }
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | Resource.prototype = Object.create(EventEmitter.prototype);
|
32 |
|
33 |
|
34 |
|
35 | Resource.prototype.query = function (values, query) {
|
36 | var ReqClass = this._Request,
|
37 | req = new ReqClass(),
|
38 | deferred = Q.defer(),
|
39 | url = util.compileRoute(this.route, values),
|
40 | self = this,
|
41 | payload;
|
42 |
|
43 | if (query) {
|
44 | url += '?' + qs.stringify(query);
|
45 | }
|
46 |
|
47 | req.open(this.method.toUpperCase(), url, true);
|
48 |
|
49 | async.mapSeries(this.middleware, function (fn, next) {
|
50 | fn.call(self, req, next);
|
51 | }, function (err) {
|
52 | if (err) { throw err; }
|
53 |
|
54 | payload = req.payload = util.formRequestPayload(req, values || {});
|
55 |
|
56 | self._sendReq(req, payload, deferred);
|
57 | });
|
58 |
|
59 | return deferred.promise;
|
60 | };
|
61 |
|
62 |
|
63 |
|
64 | Resource.prototype.use = function (fn) {
|
65 | this.middleware.push(fn);
|
66 | };
|
67 |
|
68 |
|
69 |
|
70 | Resource.prototype._sendReq = function (req, payload, deferred) {
|
71 | var self = this;
|
72 |
|
73 | req.onload = function () {
|
74 | var body = util.parseIfJSON(this.response || this.responseText),
|
75 | res = {
|
76 | status: this.status,
|
77 | body: body
|
78 | };
|
79 |
|
80 | self.emit('response', {
|
81 | status: this.status,
|
82 | body: body
|
83 | });
|
84 |
|
85 | if (this.status <= 200) {
|
86 | self.emit('success', res);
|
87 | deferred.resolve(res);
|
88 | } else {
|
89 | self.emit('failure', res);
|
90 | deferred.reject(res);
|
91 | }
|
92 | };
|
93 |
|
94 | req.onerror = function (err) {
|
95 | self.emit('error', err);
|
96 | };
|
97 |
|
98 | req.send(payload);
|
99 | };
|
100 |
|
101 | module.exports = Resource; |
\ | No newline at end of file |