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

89 lines
1.9 KiB
JavaScript

import {idFrom} from './registrar';
import SynchronizedCreatePacket from './synchronized-create.packet';
import SynchronizedDestroyPacket from './synchronized-destroy.packet';
export function SynchronizedMixin(Superclass) {
return class Synchronized extends Superclass {
constructor(...args) {
super(...args);
this._idempotentPackets = [];
}
cleanPackets() {
this._idempotentPackets = [];
}
createPacket(informed) {
const id = this.synchronizationId();
const type = idFrom(this.constructor);
return new SynchronizedCreatePacket({
synchronized: {
id,
type,
},
spec: this.toNetwork(informed),
});
}
destroy() {}
destroyPacket(informed) {
const id = this.synchronizationId();
const type = idFrom(this.constructor);
return new SynchronizedDestroyPacket({
synchronized: {
id,
type,
},
});
}
fromNetwork(json) {
this.fromJSON(json);
}
packets(informed) {
return [];
}
packetsAreIdempotent() {
return true;
}
packetsFor(informed) {
if (this._idempotentPackets.length > 0) {
return this._idempotentPackets;
}
let packets = this.packets(informed);
if (!packets) {
return [];
}
if (!Array.isArray(packets)) {
packets = [packets];
}
// Embed synchronization info.
const id = this.synchronizationId();
const type = idFrom(this.constructor);
for (let i = 0; i < packets.length; i++) {
packets[i].data.synchronized = {id, type};
}
if (this.packetsAreIdempotent()) {
this._idempotentPackets = packets;
}
return packets;
}
synchronizationId() {
return 0;
}
toNetwork(informed) {
return this.toJSON();
}
}
}