4 * Promise wrapper for OpenSRF network calls.
5 * http://docs.angularjs.org/api/ng.$q
7 * promise.notify() is called with each streamed response.
9 * promise.resolve() is called when the request is complete
10 * and passes as its value the response received from the
11 * last call to onresponse(). If no calls to onresponse()
12 * were made (i.e. no responses delivered) no value will
13 * be passed to resolve(), hence any value seen by the client
14 * will be 'undefined'.
16 * Example: Call with one response and no error checking:
18 * egNet.request(service, method, param1, param2).then(
20 * // data == undefined if no responses were received
21 * // data == null if last response was a null value
25 * Example: capture streaming responses, error checking
27 * egNet.request(service, method, param1, param2).then(
28 * function(data) { console.log('all done') },
29 * function(err) { console.log('error: ' + err) },
30 * functoin(data) { console.log('received stream response ' + data) }
34 angular.module('egCoreMod')
37 ['$q','$rootScope','egEvent',
38 function($q, $rootScope, egEvent) {
42 // raises the egAuthExpired event on NO_SESSION
43 net.checkResponse = function(resp) {
44 var content = resp.content();
45 if (!content) return null;
46 var evt = egEvent.parse(content);
47 if (evt && evt.textcode == 'NO_SESSION') {
48 $rootScope.$broadcast('egAuthExpired')
54 net.request = function(service, method) {
56 var deferred = $q.defer();
57 var params = Array.prototype.slice.call(arguments, 2);
58 console.debug('egNet ' + method);
59 new OpenSRF.ClientSession(service).request({
63 oncomplete : function() {
64 deferred.resolve(last);
66 onresponse : function(r) {
67 last = net.checkResponse(r.recv());
68 deferred.notify(last);
70 onerror : function(msg) {
71 // 'msg' currently tells us very little, so don't
72 // bother JSON-ifying it, since there is the off
73 // chance that JSON-ification could fail, e.g if
74 // the object has circular refs.
75 console.error(method +
76 ' (' + params + ') failed. See server logs.');
79 onmethoderror : function(req, statCode, statMsg) {
80 console.error('error calling method ' +
81 method + ' : ' + statCode + ' : ' + statMsg);
86 return deferred.promise;
89 // In addition to the service and method names, accepts a single array
90 // as the collection of API call parameters. This array will get
91 // expanded to individual arguments in the final server call.
92 // This is useful when the server call expects each param to be
93 // a top-level value, but the set of params is dynamic.
94 net.requestWithParamList = function(service, method, params) {
95 var args = [service, method].concat(params);
96 return net.request.apply(net, args);