UNPKG

@n1ru4l/graphql-live-query-patch

Version:

Shared logic for building live query patch implementations.

48 lines (47 loc) 1.86 kB
import { Repeater } from "@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. */ export const noDiffSymbol = Symbol("noDiffSymbol"); export const createLiveQueryPatchGenerator = (generatePatch) => (source) => new 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 === 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(); });