aboutsummaryrefslogtreecommitdiffstats
path: root/lib/webcals/request/abstract.js
blob: ac0ceb51df6b9f0fb6583b7807dc22bc98e3284d (plain) (blame)
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
(function(module, ns) {

  var SAX = ns.require('sax');
  var XHR = ns.require('xhr');


  /**
   * Creates an (Web/Cal)Dav request.
   *
   * @param {String} url location of resource.
   * @param {Object} options additional options for request.
   */
  function Abstract(url, options) {
    var key;

    if (typeof(url) === 'undefined' || !url) {
      throw new Error('request requires a url');
    }

    this.url = url;
    this.sax = new SAX();

    for (key in options) {
      if (options.hasOwnProperty(key)) {
        this[key] = options[key];
      }
    }

    this.xhr = new XHR({
      url: this.url
    });
  }

  Abstract.prototype = {

    _createPayload: function() {
      return '';
    },

    /**
     * Sends request to server.
     *
     * @param {Function} callback node style callback.
     *                            Receives three arguments
     *                            error, parsedData, xhr.
     */
    send: function(callback) {
      var self = this;
      var req = this.xhr;
      req.data = this._createPayload();

      // in the future we may stream data somehow
      req.send(function xhrResult() {
        var xhr = req.xhr;
        if (xhr.status > 199 && xhr.status < 300) {
          // success
          self.sax.write(xhr.responseText).close();

          callback(null, self.sax.root, req);
        } else {
          // fail
          callback(new Error('http error code: ' + xhr.status));
        }
      });
    }
  };

  module.exports = Abstract;

}.apply(
  this,
  (this.Webcals) ?
    [Webcals('request/abstract'), Webcals] :
    [module, require('../webcals')]
));