Skip to content

Commit e7223ac

Browse files
1 parent 0617206 commit e7223ac

File tree

3 files changed

+145
-257
lines changed

3 files changed

+145
-257
lines changed

index.js

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11

22
var Emitter = require('component-emitter');
33

4+
exports.protocol = 5;
5+
46
/**
57
* Packet types (see https://github.com/socketio/socket.io-protocol)
68
*/
79

8-
exports.CONNECT = 0;
9-
exports.DISCONNECT = 1;
10-
exports.EVENT = 2;
11-
exports.ACK = 3;
12-
exports.ERROR = 4;
13-
exports.BINARY_EVENT = 5;
14-
exports.BINARY_ACK = 6;
10+
var PacketType = (exports.PacketType = {
11+
CONNECT: 0,
12+
DISCONNECT: 1,
13+
EVENT: 2,
14+
ACK: 3,
15+
CONNECT_ERROR: 4
16+
});
1517

1618
var isInteger = Number.isInteger || function (value) {
1719
return typeof value === 'number' &&
@@ -21,10 +23,14 @@ var isInteger = Number.isInteger || function (value) {
2123

2224
var isString = function (value) { return typeof value === 'string'; };
2325

26+
var isObject = function (value) {
27+
return Object.prototype.toString.call(value) === '[object Object]';
28+
};
29+
2430
function Encoder () {}
2531

26-
Encoder.prototype.encode = function (packet, callback) {
27-
return callback([ JSON.stringify(packet) ]);
32+
Encoder.prototype.encode = function (packet) {
33+
return [ JSON.stringify(packet) ];
2834
};
2935

3036
function Decoder () {}
@@ -33,11 +39,12 @@ Emitter(Decoder.prototype);
3339

3440
function isDataValid (decoded) {
3541
switch (decoded.type) {
36-
case exports.CONNECT:
37-
case exports.DISCONNECT:
42+
case PacketType.CONNECT:
43+
return decoded.data === undefined || isObject(decoded.data);
44+
case PacketType.DISCONNECT:
3845
return decoded.data === undefined;
39-
case exports.ERROR:
40-
return isString(decoded.data);
46+
case PacketType.CONNECT_ERROR:
47+
return isObject(decoded.data);
4148
default:
4249
return Array.isArray(decoded.data);
4350
}
@@ -46,7 +53,7 @@ function isDataValid (decoded) {
4653
Decoder.prototype.add = function (obj) {
4754
var decoded = JSON.parse(obj);
4855

49-
var isTypeValid = isInteger(decoded.type) && decoded.type >= exports.CONNECT && decoded.type <= exports.BINARY_ACK;
56+
var isTypeValid = isInteger(decoded.type) && decoded.type >= PacketType.CONNECT && decoded.type <= PacketType.CONNECT_ERROR;
5057
if (!isTypeValid) {
5158
throw new Error('invalid packet type');
5259
}

0 commit comments

Comments
 (0)