forked from plainblack/Lacuna-Web-Client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.js
341 lines (299 loc) · 12.5 KB
/
rpc.js
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/**
* Code taken from inputEx's (http://javascript.neyric.com/inputex/) rpc library and slightly modified
*/
YAHOO.namespace("rpc");
if (typeof YAHOO.rpc.Service == "undefined" || !YAHOO.rpc.Service) {
(function() {
var Lang = YAHOO.lang,
Util = YAHOO.util;
var Service = function(smd, callback, baseUrl) {
if( Lang.isString(smd) ) {
this.smdUrl = smd;
this.fetch(smd, callback);
}
else if( Lang.isObject(smd) ) {
this._smd = smd;
this._baseUrl = baseUrl;
this.process(callback);
}
else {
throw new Error("smd should be an object or an url");
}
};
Service.prototype = {
/**
* Generate the function from a service definition
* @method _generateService
* @param {String} serviceName
* @param {Method definition} method
*/
_generateService: function(serviceName, method) {
if(this[method]){
throw new Error("WARNING: "+ serviceName+ " already exists for service. Unable to generate function");
}
method.name = serviceName;
var self = this;
var func = function(oParams, opts) {
var smd = self._smd;
var baseUrl = self._baseUrl;
var envelope = YAHOO.rpc.Envelope[method.envelope || smd.envelope];
var callback = {
success: function(o) {
//YAHOO.log(o, "debug", "RPC.SUCCESS");
var results = envelope.deserialize(o);
opts.success.call(opts.scope || self, results);
},
failure: function(o) {
//YAHOO.log(o, "debug", "RPC.FAILURE");
if(Lang.isFunction(opts.failure) ) {
var results;
try {
results = envelope.deserialize(o);
}
catch(e) {
results = o;
}
opts.failure.call(opts.scope || self, results);
}
},
scope: self
};
if(opts.timeout) {
callback.timeout = opts.timeout;
}
var params, //will be either an Array or an Object depending on the type that method.parameters is
pKey, i, p;
//if this is array params
if(Lang.isArray(method.parameters)) {
params = [];
if(smd.additionalParameters && Lang.isArray(smd.parameters)) {
for(i = 0 ; i < smd.parameters.length ; i++) {
p = smd.parameters[i];
params.push(p["default"]);
}
}
//push method params in correct order
for(i = 0 ; i < method.parameters.length ; i++) {
p = method.parameters[i];
params.push(oParams[p.name]);
}
}
else {
//other wise it's an object format and we don't care what order they are in
params = {};
//apply any additonal params
if(smd.additionalParameters && Lang.isArray(smd.parameters)) {
for(i = 0 ; i < smd.parameters.length ; i++) {
p = smd.parameters[i];
params[p.name] = p["default"];
}
}
//augment with passing params after additional so we overwrite if we have to
Lang.augmentObject(params, oParams, true);
}
/* 1.1 implementation
var params = {};
if(smd.additionalParameters && Lang.isArray(smd.parameters) ) {
for(var i = 0 ; i < smd.parameters.length ; i++) {
var p = smd.parameters[i];
params[p.name] = p["default"];
}
}
Lang.augmentObject(params, data, true);
*/
var url = opts.target || method.target || smd.target;
var urlRegexp = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/i;
if(smd.target && !url.match(urlRegexp) && url != smd.target) {
url = smd.target+url;
}
if( !!this.smdUrl && !url.match(urlRegexp) ) {
// URL is still relative !
var a=this.smdUrl.split('/');
a[a.length-1]="";
url = a.join("/")+url;
}
else if ( baseUrl ) {
baseUrl = baseUrl.replace(/\/?$/,'/');
url = url.replace(/^\//, baseUrl);
}
var r = {
target: url,
callback: callback,
data: params,
origData: oParams,
opts: opts,
callbackParamName: method.callbackParamName || smd.callbackParamName,
transport: method.transport || smd.transport
};
var serialized = envelope.serialize(smd, method, params);
Lang.augmentObject(r, serialized, true);
return YAHOO.rpc.Transport[r.transport].call(self, r);
};
func.name = serviceName;
func.description = method.description;
func._parameters = method.parameters;
return func;
},
/**
* Process the SMD definition
* @method process
*/
process: function(callback) {
var serviceDefs = this._smd.services;
// Generate the methods to this object
for(var serviceName in serviceDefs){
if( serviceDefs.hasOwnProperty(serviceName) ) {
// Get the object that will contain the method.
// handles "namespaced" services by breaking apart by '.'
var current = this;
var pieces = serviceName.split(".");
for(var i=0; i< pieces.length-1; i++){
current = current[pieces[i]] || (current[pieces[i]] = {});
}
current[pieces[pieces.length-1]] = this._generateService(serviceName, serviceDefs[serviceName]);
}
}
// call the success handler
if(Lang.isObject(callback) && Lang.isFunction(callback.success)) {
callback.success.call(callback.scope || this);
}
},
/**
* Download the SMD at the given url
* @method fetch
* @param {String} Absolute or relative url
*/
fetch: function(url, callback) {
if(YAHOO.rpc.Service._smdCache[url]) {
this._smd = YAHOO.rpc.Service._smdCache[url];
this.process(callback);
}
else {
// TODO: if url is not in the same domain, we should use jsonp !
Util.Connect.asyncRequest('GET', url, {
success: function(o) {
try {
this._smd = Lang.JSON.parse(o.responseText);
YAHOO.rpc.Service._smdCache[url] = this._smd;
this.process(callback);
}
catch(ex) {
//YAHOO.log(ex);
if( Lang.isFunction(callback.failure) ) {
callback.failure.call(callback.scope || this, {error: ex});
}
}
},
failure: function(o) {
if( Lang.isFunction(callback.failure) ) {
callback.failure.call(callback.scope || this, {error: "unable to fetch url "+url});
}
},
scope: this
});
}
}
};
Service._smdCache = {}; //collection of smd objects by URL
Service._requestId = 1;
/**
* YAHOO.rpc.Transport
* @class YAHOO.rpc.Transport
* @static
*/
YAHOO.rpc.Transport = {
/**
* Build a ajax request using 'POST' method
* @method POST
* @param {Object} r Object specifying target, callback and data attributes
*/
"POST": function(r) {
return Util.Connect.asyncRequest('POST', r.target, r.callback, r.data );
},
/**
* Build a ajax request using 'GET' method
* @method GET
* @param {Object} r Object specifying target, callback and data attributes
*/
"GET": function(r) {
return Util.Connect.asyncRequest('GET', r.target + (r.data ? '?'+r.data : ''), r.callback, '');
},
jsonp_id: 0,
/**
* Receive data through JSONP (insert a script tag within the page)
* @method JSONP
* @param {Object} r Object specifying target, callback and data attributes
*/
"JSONP": function(r) {
r.callbackParamName = r.callbackParamName || "callback";
var fctName = encodeURIComponent("YAHOO.rpc.Transport.JSONP.jsonpCallback"+YAHOO.rpc.Transport.jsonp_id);
YAHOO.rpc.Transport.JSONP["jsonpCallback"+YAHOO.rpc.Transport.jsonp_id] = function(results) {
if(Lang.isObject(r.callback) && Lang.isFunction(r.callback.success)) {
r.callback.success.call(r.callback.scope || this, results);
}
};
YAHOO.rpc.Transport.jsonp_id+=1;
return Util.Get.script( r.target + ((r.target.indexOf("?") == -1) ? '?' : '&') + r.data + "&"+r.callbackParamName+"="+fctName);
}
};
/**
* YAHOO.rpc.Envelope
* @class YAHOO.rpc.Envelope
* @static
*/
YAHOO.rpc.Envelope = {
/**
* JSON-RPC-2.0 envelope
* @class YAHOO.rpc.Envelope.JSON-RPC-2.0
* @static
*/
"JSON-RPC-2.0": {
/**
* serialize
*/
serialize: function(smd, method, data) {
return {
data: Lang.JSON.stringify({
"id": YAHOO.rpc.Service._requestId++,
"method": method.name,
"jsonrpc": "2.0",
"params": data
})
};
},
/**
* deserialize
*/
deserialize: function(results) {
if(results.getResponseHeader && (results.getResponseHeader["Content-Type"] == "application/json-rpc" || results.getResponseHeader["Content-Type"] == "application/json")) {
return Lang.JSON.parse(results.responseText);
}
else {
if(results.status == -1) {
return {"error":{"message":"The Request has been Aborted because it was taking too long."}};
}
else if(results.status === 0) {
return {"error":{"message":"Communication with the server has been interrupted for an unknown reason."}};
}
else {
// YUI loses headers for Cross-Origin requests, so try as JSON anyway
try {
return Lang.JSON.parse(results.responseText);
}
catch(e) {
return {"error":{"message":"Response Content-Type is not JSON"}};
}
}
}
}
}
};
//set connects post header to json
Util.Connect.setDefaultPostHeader("application/json");
Util.Connect.setDefaultPostHeader(true);
//assign to global
YAHOO.rpc.Service = Service;
})();
YAHOO.register("rpc", YAHOO.rpc.Service, {version: "1", build: "0"});
}
// vim: noet:ts=4:sw=4