forked from beevelop/ng-stomp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ng-stomp.js
76 lines (66 loc) · 2.26 KB
/
ng-stomp.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
/**
* ngStomp
*
* @version 0.0.1-alpha.1
* @author Maik Hummel <yo@beevelop.com>
* @license WTFPL
*/
angular
.module('ngStomp', [])
.service('$stomp', [
'$rootScope', '$q',
function ($rootScope, $q) {
this.sock = null;
this.stomp = null;
this.debug = null;
this.setDebug = function (callback) {
this.debug = callback;
};
this.connect = function (endpoint, headers) {
headers = headers || {};
var dfd = $q.defer();
this.sock = new SockJS(endpoint);
this.stomp = Stomp.over(this.sock);
this.stomp.debug = this.debug;
this.stomp.connect(headers, function (frame) {
dfd.resolve(frame);
}, function (err) {
dfd.reject(err);
});
return dfd.promise;
};
this.disconnect = function () {
var dfd = $q.defer();
this.stomp.disconnect(dfd.resolve);
return dfd.promise;
};
this.subscribe = this.on = function (destination, callback, headers) {
headers = headers || {};
return this.stomp.subscribe(destination, function (res) {
var payload = null;
try {
payload = JSON.parse(res.body);
} finally {
if (callback) {
callback(payload, res.headers, res);
}
}
}, headers);
};
this.unsubscribe = this.off = function (subscription) {
subscription.unsubscribe();
};
this.send = function (destination, body, headers) {
var dfd = $q.defer();
try {
var payloadJson = JSON.stringify(body);
headers = headers || {};
this.stomp.send(destination, headers, payloadJson);
dfd.resolve();
} catch (e) {
dfd.reject(e);
}
return dfd.promise;
};
}]
);