avocado-old/packages/net/s13n/server.js

74 lines
2.0 KiB
JavaScript
Raw Normal View History

2019-09-30 20:08:05 -05:00
import {idFromSynchronized} from './registry';
2019-09-22 18:45:33 -05:00
import {SynchronizedCreatePacket} from './synchronized-create.packet';
import {SynchronizedDestroyPacket} from './synchronized-destroy.packet';
export class ServerSynchronizer {
constructor() {
this._added = [];
this._removed = [];
this._synchronized = {};
this._synchronizedFlat = [];
}
addSynchronized(synchronized) {
if (this.hasSynchronized(synchronized)) {
return;
}
else {
this._added.push(synchronized);
}
const type = idFromSynchronized(synchronized.constructor);
if (!(type in this._synchronized)) {
this._synchronized[type] = new Map();
}
this._synchronizedFlat.push(synchronized);
const synchronizationId = synchronized.synchronizationId();
this._synchronized[type].set(synchronizationId, synchronized);
}
destroy() {}
hasSynchronized(synchronized) {
return -1 !== this._synchronizedFlat.indexOf(synchronized);
}
removeSynchronized(synchronized) {
if (!this.hasSynchronized(synchronized)) {
return;
}
else {
this._removed.push(synchronized);
}
const index = this._synchronizedFlat.indexOf(synchronized);
this._synchronizedFlat.splice(index, 1);
const type = idFromSynchronized(synchronized.constructor);
const synchronizationId = synchronized.synchronizationId();
this._synchronized[type].delete(synchronizationId);
}
packetsFor(informed) {
const payload = [];
for (let i = 0; i < this._synchronizedFlat.length; i++) {
const synchronized = this._synchronizedFlat[i];
if (-1 !== this._added.indexOf(synchronized)) {
2019-09-30 20:08:05 -05:00
payload.push(synchronized.createPacket(informed));
2019-09-22 18:45:33 -05:00
}
else if (-1 !== this._removed.indexOf(synchronized)) {
2019-09-30 20:08:05 -05:00
payload.push(synchronized.destroyPacket(informed));
2019-09-22 18:45:33 -05:00
}
else {
const packets = synchronized.packetsFor(informed);
for (let j = 0; j < packets.length; j++) {
2019-10-01 22:42:41 -05:00
payload.push(packets[j]);
2019-09-22 18:45:33 -05:00
}
}
}
this._added = [];
this._removed = [];
return payload;
}
}