avocado-old/packages/net/packet/packet.js
2020-05-21 08:57:13 -05:00

56 lines
1.3 KiB
JavaScript

import {idFromPacket} from './registry';
import schemapack from 'schemapack';
export class Packet {
constructor(data = {}) {
this.data = data;
}
static get builder() {
if (!this._builder) {
const schema = this.schema;
if (!schema._id) {
throw new Error([
`No packet id found in '${this.name}.schema'. This is usually due to forgetting to`,
'inherit from Packet.schema within your packet subclass schema definition.',
].join(' '));
}
if (!schema.data) {
throw new Error([
`No data found in '${this.name}.schema'. This is usually due to forgetting to`,
'inherit from Packet.schema within your packet subclass schema definition.',
].join(' '));
}
this._builder = schemapack.build(schema);
}
return this._builder;
}
static pack(packet) {
return this.builder.encode({
_id: packet.data[0],
data: packet.data[1],
});
}
static packPacket(packet) {
const id = idFromPacket(packet.constructor);
return packet.constructor.pack({
data: [id, packet.data],
});
}
static get schema() {
return {
_id: 'uint8',
};
}
static unpack(packet) {
const {data} = this.builder.decode(packet);
return data;
}
}