avocado-old/packages/net/packet/packet.js
2020-06-17 04:35:59 -05:00

50 lines
1.0 KiB
JavaScript

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(' '));
}
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 {idFrom} = require('./registrar');
const id = idFrom(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;
}
}