forked from SocketCluster/socketcluster-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse.js
55 lines (47 loc) · 1.18 KB
/
response.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
var scErrors = require('sc-errors');
var InvalidActionError = scErrors.InvalidActionError;
var Response = function (socket, id) {
this.socket = socket;
this.id = id;
this.sent = false;
};
Response.prototype._respond = function (responseData, options) {
if (this.sent) {
throw new InvalidActionError('Response ' + this.id + ' has already been sent');
} else {
this.sent = true;
this.socket.sendObject(responseData, options);
}
};
Response.prototype.end = function (data, options) {
if (this.id) {
var responseData = {
rid: this.id
};
if (data !== undefined) {
responseData.data = data;
}
this._respond(responseData, options);
}
};
Response.prototype.error = function (error, data, options) {
if (this.id) {
var err = scErrors.dehydrateError(error);
var responseData = {
rid: this.id,
error: err
};
if (data !== undefined) {
responseData.data = data;
}
this._respond(responseData, options);
}
};
Response.prototype.callback = function (error, data, options) {
if (error) {
this.error(error, data, options);
} else {
this.end(data, options);
}
};
module.exports.Response = Response;