2019-04-28 23:45:03 -05:00
|
|
|
import {compose, EventEmitter} from '@avocado/core';
|
2019-04-11 15:26:13 -05:00
|
|
|
|
2019-04-25 00:09:03 -05:00
|
|
|
import {packetFromId} from './registry';
|
2019-04-11 15:26:13 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Packet types (see https://github.com/socketio/socket.io-protocol)
|
|
|
|
*/
|
|
|
|
const TYPES = {
|
|
|
|
EVENT: 2,
|
|
|
|
ERROR: 4,
|
|
|
|
BINARY_EVENT: 5,
|
|
|
|
};
|
|
|
|
|
|
|
|
class Encoder {
|
|
|
|
|
|
|
|
encode(packet, callback) {
|
|
|
|
switch (packet.type) {
|
|
|
|
case TYPES.EVENT:
|
|
|
|
case TYPES.BINARY_EVENT:
|
|
|
|
return callback([this.pack(packet)]);
|
|
|
|
default:
|
|
|
|
return callback([JSON.stringify(packet)]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pack(packet) {
|
2019-04-25 00:09:03 -05:00
|
|
|
const packetId = packet.data[0];
|
|
|
|
const Packet = packetFromId(packetId);
|
|
|
|
return Packet.pack(packet);
|
2019-04-11 15:26:13 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
const decorateDecoder = compose(
|
|
|
|
EventEmitter,
|
|
|
|
);
|
|
|
|
|
|
|
|
class Decoder extends decorateDecoder(class {}) {
|
|
|
|
|
|
|
|
add(obj) {
|
|
|
|
if (typeof obj === 'string') {
|
|
|
|
this.parseJSON(obj);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
this.parseBinary(obj);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
destroy() {}
|
|
|
|
|
2019-04-25 00:09:03 -05:00
|
|
|
parseBinary(packet) {
|
|
|
|
const view = new Uint8Array(packet);
|
2019-04-11 15:26:13 -05:00
|
|
|
const packetId = view[0];
|
2019-04-25 00:09:03 -05:00
|
|
|
const Packet = packetFromId(packetId);
|
|
|
|
const data = Packet.unpack(packet);
|
|
|
|
this.emit('decoded', {
|
|
|
|
type: TYPES.EVENT,
|
|
|
|
data: [packetId, data],
|
|
|
|
nsp: '/',
|
|
|
|
});
|
2019-04-11 15:26:13 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
parseJSON(obj) {
|
2019-04-14 15:32:17 -05:00
|
|
|
let decoded;
|
2019-04-11 15:26:13 -05:00
|
|
|
try {
|
2019-04-14 15:32:17 -05:00
|
|
|
decoded = JSON.parse(obj);
|
2019-04-11 15:26:13 -05:00
|
|
|
}
|
|
|
|
catch (e) {
|
2019-04-14 15:32:17 -05:00
|
|
|
decoded = errorPacket;
|
2019-04-11 15:26:13 -05:00
|
|
|
}
|
2019-04-14 15:32:17 -05:00
|
|
|
this.emit('decoded', decoded);
|
2019-04-11 15:26:13 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export {Decoder, Encoder};
|