From 7a850ac60d382cce6ca94dea5d86ca2850da2402 Mon Sep 17 00:00:00 2001 From: Lenz Weber-Tronic Date: Mon, 6 Nov 2023 15:44:03 +0100 Subject: [PATCH] Add `reset` method to `print`, hook up to `ApolloCache.gc` --- .changeset/wild-dolphins-jog.md | 5 +++++ src/cache/inmemory/inMemoryCache.ts | 2 ++ src/utilities/graphql/print.ts | 29 ++++++++++++++++++++--------- 3 files changed, 27 insertions(+), 9 deletions(-) create mode 100644 .changeset/wild-dolphins-jog.md diff --git a/.changeset/wild-dolphins-jog.md b/.changeset/wild-dolphins-jog.md new file mode 100644 index 00000000000..589af17940c --- /dev/null +++ b/.changeset/wild-dolphins-jog.md @@ -0,0 +1,5 @@ +--- +"@apollo/client": patch +--- + +Add `reset` method to `print`, hook up to `ApolloCache.gc` diff --git a/src/cache/inmemory/inMemoryCache.ts b/src/cache/inmemory/inMemoryCache.ts index 3fd230b94e0..3fe7ab56fdf 100644 --- a/src/cache/inmemory/inMemoryCache.ts +++ b/src/cache/inmemory/inMemoryCache.ts @@ -17,6 +17,7 @@ import { isReference, DocumentTransform, canonicalStringify, + print, } from "../../utilities/index.js"; import type { InMemoryCacheConfig, NormalizedCacheObject } from "./types.js"; import { StoreReader } from "./readFromStore.js"; @@ -293,6 +294,7 @@ export class InMemoryCache extends ApolloCache { resetResultIdentities?: boolean; }) { canonicalStringify.reset(); + print.reset(); const ids = this.optimisticData.gc(); if (options && !this.txCount) { if (options.resetResultCache) { diff --git a/src/utilities/graphql/print.ts b/src/utilities/graphql/print.ts index 5fb1cb68599..d90a15611d0 100644 --- a/src/utilities/graphql/print.ts +++ b/src/utilities/graphql/print.ts @@ -1,14 +1,25 @@ +import type { ASTNode } from "graphql"; import { print as origPrint } from "graphql"; import { canUseWeakMap } from "../common/canUse.js"; -const printCache = canUseWeakMap ? new WeakMap() : undefined; -export const print: typeof origPrint = (ast) => { - let result; - result = printCache?.get(ast); +let printCache: undefined | WeakMap; +// further TODO: replace with `optimism` with a `WeakCache` once those are available +export const print = Object.assign( + (ast: ASTNode) => { + let result; + result = printCache?.get(ast); - if (!result) { - result = origPrint(ast); - printCache?.set(ast, result); + if (!result) { + result = origPrint(ast); + printCache?.set(ast, result); + } + return result; + }, + { + reset() { + printCache = canUseWeakMap ? new WeakMap() : undefined; + }, } - return result; -}; +); + +print.reset();