gqty
Version:
The No-GraphQL Client for TypeScript
68 lines (65 loc) • 2.14 kB
JavaScript
import { Cache } from '../Cache/index.mjs';
const createContext = ({
aliasLength,
cache,
cachePolicy,
depthLimit,
scalars,
schema,
typeKeys
}) => {
const disposeSubscriptions = /* @__PURE__ */ new Set();
const selectSubscriptions = /* @__PURE__ */ new Set();
return {
aliasLength,
cache: cachePolicy === "no-cache" || cachePolicy === "no-store" || cachePolicy === "reload" ? new Cache(void 0, { maxAge: 0 }) : cache,
cacheOptions: {
includeExpired: cachePolicy === "default" || cachePolicy === "force-cache" || cachePolicy === "only-if-cached"
},
scalars,
schema,
depthLimit,
hasCacheHit: false,
hasCacheMiss: false,
shouldFetch: false,
notifyCacheUpdate: cachePolicy !== "default",
select(selection, cacheNode) {
const now = Date.now();
const { data, expiresAt: age = Infinity } = cacheNode != null ? cacheNode : {};
if (cacheNode) {
this.shouldFetch || (this.shouldFetch = data === void 0 || // Add 100 ms leeway to avoiding infinite fetch loops for caches with
// immedidate staleness.
age < now);
this.hasCacheHit || (this.hasCacheHit = data !== void 0);
this.notifyCacheUpdate || (this.notifyCacheUpdate = data === void 0);
}
this.hasCacheMiss || (this.hasCacheMiss = (cacheNode == null ? void 0 : cacheNode.data) === void 0);
selectSubscriptions.forEach((fn) => fn(selection, cacheNode));
},
reset() {
this.shouldFetch = false;
this.hasCacheHit = false;
this.hasCacheMiss = false;
this.notifyCacheUpdate = cachePolicy !== "default";
},
subscribeSelect(callback) {
selectSubscriptions.add(callback);
return () => {
selectSubscriptions.delete(callback);
};
},
dispose() {
disposeSubscriptions.forEach((fn) => fn());
disposeSubscriptions.clear();
selectSubscriptions.clear();
},
subscribeDispose(callback) {
disposeSubscriptions.add(callback);
return () => {
disposeSubscriptions.delete(callback);
};
},
typeKeys
};
};
export { createContext };