@n1ru4l/graphql-live-query-patch
Version:
Shared logic for building live query patch implementations.
52 lines (51 loc) • 2.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLiveQueryPatchGenerator = exports.noDiffSymbol = void 0;
const repeater_1 = require("@repeaterjs/repeater");
/**
* Symbol that indicates that there is no diff between the previous and current state and thus no patch must be sent to the client.
* This value should be returned from GeneratePatchFunction.
*/
exports.noDiffSymbol = Symbol("noDiffSymbol");
const createLiveQueryPatchGenerator = (generatePatch) => (source) => new repeater_1.Repeater(async (push, stop) => {
var _a, _b;
const iterator = source[Symbol.asyncIterator]();
stop.then(() => { var _a; return (_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator); });
let previousValue = null;
let revision = 1;
let next;
while ((next = await iterator.next()).done === false) {
// if it is not live we simply forward everything :)
if (!next.value.isLive) {
await push(next.value);
continue;
}
const valueToPublish = {};
if (previousValue) {
const currentValue = (_a = next.value.data) !== null && _a !== void 0 ? _a : {};
const patch = generatePatch(previousValue, currentValue);
previousValue = currentValue;
if (patch === exports.noDiffSymbol) {
continue;
}
valueToPublish.patch = patch;
revision++;
}
else {
previousValue = (_b = next.value.data) !== null && _b !== void 0 ? _b : {};
if ("data" in next.value) {
valueToPublish.data = previousValue;
}
}
if ("errors" in next.value) {
valueToPublish.errors = next.value.errors;
}
if ("extensions" in next.value) {
valueToPublish.extensions = next.value.extensions;
}
valueToPublish.revision = revision;
await push(valueToPublish);
}
stop();
});
exports.createLiveQueryPatchGenerator = createLiveQueryPatchGenerator;