Posts Tagged ‘JSON-RPC’

JSON-RPC 2.0 Implementation

Saturday, December 5th, 2009

Here’s another quick braindump post. A custom JSON-RPC library I wrote for a project at my last job. It should follow the JSON-RPC 2.0 Spec pretty closely. It does require the jQuery library as well.

You can pretty much ignore the MIKU references. Basically it’s just a way of namespacing objects to make them globally available. Try reading up on the YUI library for more information.

As always, feel free to post with any questions.

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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
var MIKU;
 
/*
 * Method to allow namespacing of new objects within MIKU;
 *
 * Example:
 * MIKU.namespace('objectname');
 * MIKU.objectname = function() { return {'...'} }
 *
 */
MIKU = function() {
  return {
    namespace: function(name) {
      try {
        if (MIKU[name]) {
          throw 'Namespace exists.';
        }
        return {}
      }
      catch (e) {
        this.throwError(e);
      }
    }
  }
}();
 
MIKU.namespace('throwError');
 
/*
 * Method to catch MIKU errors
 */
MIKU.throwError = function(e) {
  if (console) {
    console.error((e.message || 'MikuError:'), e);
  }
};
 
/*
 * Init the JsonRpc namespace into the MIKU object.
 */
MIKU.namespace('JsonRpc');
 
/*
 * Miku Json-RPC Implementation
 */
 
MIKU.JsonRpc = function() {
  var _url = 'json-rpc/call';
  var _timeout = false;
  var _requests = [];
  var _responses = [];
  var _callbacks = {};
  var _requestId = 0;
  var _failures = 0;
 
  function _send() {
    _request();
    _t = false;
    _requests = [];
  }
 
  function _request() {
    try {
      if (!_url) {
        throw('undefined post url.');
      }
      $.ajax({
        type: 'POST',
        url: _url,
        data: ({
          request: JSON.stringify(_requests)
        }),
        dataFilter: function(data, type) {
          //check for php errors
          try {
            return JSON.parse(data);
          }
          catch (e) {
            var phpError = /^.*?(Error|Warning|Notice).*?\:\s*(.*?) in .*?(\/[0-9A-Za-z\/\.\-\_\ ]+).* on line .*?([0-9]+).*$/i;
            var lines = data.split(/\n/g);
            $.each(lines, function() {
              var error = this.match(phpError);
              if (error) {
                MIKU.throwError({
                  message: error[1] + ': ' + error[2],
                  file: error[3],
                  line: error[4]
                });
              }
            });
          }
        },
        success: function(data) {
          _success(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          // retry after connection failures
          if (XMLHttpRequest.status != '200') {
            _failures ++;
            if (_failures < 3) {
              _request();
              return;
            }
          }
 
          // give up and throw errors...
          MIKU.throwError([XMLHttpRequest, textStatus, errorThrown]);
        }
      });
    }
    catch(e) {
      MIKU.throwError(e);
    }
  }
 
  function _success(response) {
    $.each(jQuery.makeArray(response), function() {
      try {
        if (this.error) {
          // check for error
          throw(this.error);
        }
        else if(this.result) {
          // trigger callback
          var callback = _callbacks[this.id];
          callback(this.result);
        }
      }
      catch(e) {
        MIKU.throwError(e);
      }
    });
 
    // reset callbacks
    _callbacks = {};
  }
 
  function _genId() {
    return ++_requestId;
  }
 
  return {
    version: '2.0',
    delay: 10,
    setUrl: function(url) {
      _url = url;
    },
    call: function(args) {
      var id = _genId();
 
      var request = {
        jsonrpc: this.version,
        method: args.method,
        params: args.params,
        id: id
      }
 
      _requests.push(request);
      _callbacks[id] = args.onSuccess;
 
      if (_timeout) {
        clearTimeout(_timeout);
      }
      _timeout = setTimeout(_send, this.delay);
 
      return request;
    }
  }
}();
 
/*
 * Testing Below
 */
 
$(document).ready(function() {
  var rpc = MIKU.JsonRpc;
 
/*
  rpc.call({
    method: 'System.getTitle',
    params: [
      'this is a title'
    ],
    onSuccess: function() {
      console.log('w00t');
    }
  });
*/
});