UNPKG

@aotimme/urql-exchange-refetch-interval

Version:

An exchange that allows refetching queries at a specified interval

102 lines (96 loc) 3.1 kB
'use strict'; function start(e) { return { tag: 0, 0: e }; } function onPush(e) { return r => t => { var i = !1; r((r => { if (i) ; else if (0 === r) { i = !0; t(0); } else if (0 === r.tag) { var a = r[0]; t(start((e => { if (1 === e) { i = !0; } a(e); }))); } else { e(r[0]); t(r); } })); }; } var pipe = (...e) => { var r = e[0]; for (var t = 1, i = e.length; t < i; t++) { r = e[t](r); } return r; }; const DEFAULT_REFETCH_INTERVAL = 5 * 60 * 1000; /** Exchange factory that refetches all queries on an interval. * * @param options - An {@link Options} configuration object. * @returns the created refetch-interval {@link Exchange}. * * @example * ```ts * refetchIntervalExchange({ * // Refetch every second. * refetchInterval: 1000, * }); * ``` */ const refetchIntervalExchange = (options) => { return ({ client, forward }) => { const operations = new Map(); const getRefetchInterval = (op) => { const refetchInterval = typeof options.refetchInterval === "function" ? options.refetchInterval(op) : options.refetchInterval; if (typeof refetchInterval === "undefined") { return DEFAULT_REFETCH_INTERVAL; } else if (typeof refetchInterval === "boolean") { return refetchInterval ? DEFAULT_REFETCH_INTERVAL : 0; } return refetchInterval; }; return (ops$) => { if (typeof window === 'undefined') { return forward(ops$); } const processIncomingOperation = (op) => { const currentOperationAndTimeout = operations.get(op.key); if (op.kind === 'query') { if (currentOperationAndTimeout) { clearTimeout(currentOperationAndTimeout.timeoutId); operations.delete(op.key); } const refetchInterval = getRefetchInterval(op); if (refetchInterval > 0) { const timeoutId = setTimeout(() => { const requestOperation = client.createRequestOperation('query', op, { ...op.context, requestPolicy: 'cache-and-network', }); client.reexecuteOperation(requestOperation); }, refetchInterval); operations.set(op.key, { operation: op, timeoutId }); } } if (op.kind === 'teardown' && currentOperationAndTimeout) { clearTimeout(currentOperationAndTimeout.timeoutId); operations.delete(op.key); } }; return forward(pipe(ops$, onPush(processIncomingOperation))); }; }; }; exports.refetchIntervalExchange = refetchIntervalExchange;