1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | var define = require('./define');
|
8 | var utils = require('./utils');
|
9 |
|
10 |
|
11 | function CloudsProtocol (sender) {
|
12 | this.sender = sender;
|
13 | this._debug = utils.debug('protocol:' + sender);
|
14 | this._debug('create');
|
15 | }
|
16 |
|
17 | CloudsProtocol.prototype._toString = function (d) {
|
18 | return {
|
19 | params: d,
|
20 | raw: JSON.stringify(d)
|
21 | };
|
22 | };
|
23 |
|
24 | CloudsProtocol.prototype.packMessage = function (content) {
|
25 | this._debug('packMessage: %s', content);
|
26 | return this._toString({
|
27 | t: 'm',
|
28 | s: this.sender,
|
29 | d: content
|
30 | });
|
31 | };
|
32 |
|
33 | CloudsProtocol.prototype.packCall = function (method, args) {
|
34 | var messageId = utils.randomString(8);
|
35 | this._debug('packCall: %s, %s, %s', messageId, method, args);
|
36 | return this._toString({
|
37 | t: 'c',
|
38 | s: this.sender,
|
39 | d: {
|
40 | i: messageId,
|
41 | m: method,
|
42 | a: args
|
43 | }
|
44 | });
|
45 | };
|
46 |
|
47 | CloudsProtocol.prototype.packResult = function (messageId, err, result) {
|
48 | this._debug('packResult: %s, %s', messageId, result);
|
49 | return this._toString({
|
50 | t: 'r',
|
51 | s: this.sender,
|
52 | d: {
|
53 | i: messageId,
|
54 | e: this._packErrorMessage(err || null),
|
55 | r: result
|
56 | }
|
57 | });
|
58 | };
|
59 |
|
60 | CloudsProtocol.prototype.unpack = function (str) {
|
61 | this._debug('unpack: %s', str);
|
62 | var data = JSON.parse(str);
|
63 |
|
64 | if (data.t === 'r' && data.d.e) {
|
65 | data.d.e = this._unpackErrorMessage(data.d.e);
|
66 | }
|
67 |
|
68 | var ret = {
|
69 | type: data.t,
|
70 | sender: data.s,
|
71 | data: data.d,
|
72 | raw: str
|
73 | };
|
74 |
|
75 | return ret;
|
76 | };
|
77 |
|
78 | CloudsProtocol.prototype._unpackErrorMessage = function (e) {
|
79 |
|
80 | var err = new Error(e.message);
|
81 | Object.keys(e).forEach(function (k) {
|
82 | err[k] = e[k];
|
83 | });
|
84 | return err;
|
85 | };
|
86 |
|
87 | CloudsProtocol.prototype._packErrorMessage = function (err) {
|
88 | if (!err) return err;
|
89 | var e = {};
|
90 | e.message = err.message;
|
91 | try {
|
92 | Object.keys(err).forEach(function (k) {
|
93 | e[k] = err[k];
|
94 | });
|
95 | } catch (err) {
|
96 | this._debug('_packErrorMessage: %s', err);
|
97 | }
|
98 | return e;
|
99 | };
|
100 |
|
101 |
|
102 | module.exports = CloudsProtocol;
|