Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Follow-up to #6655 #6664

Merged
merged 1 commit into from Jul 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -95,14 +95,12 @@ interface Options<TContext = Record<string, any>> {
// and that all relevant data will be found by the kind of iteration performed by
// `JSON.stringify`, but you should not assume anything about the particular fields on
// `keyData`.
generateCacheKey?: GenerateCacheKeyFunction;
generateCacheKey?(
requestContext: GraphQLRequestContext<Record<string, any>>,
keyData: unknown,
): string;
}

type GenerateCacheKeyFunction = (
requestContext: GraphQLRequestContext<Record<string, any>>,
keyData: unknown,
) => string;

enum SessionMode {
NoSession,
Private,
Expand All @@ -113,18 +111,28 @@ function sha(s: string) {
return createHash('sha256').update(s).digest('hex');
}

interface BaseCacheKey {
interface BaseCacheKeyData {
source: string;
operationName: string | null;
variables: { [name: string]: any };
extra: any;
}

interface ContextualCacheKey {
interface ContextualCacheKeyData {
sessionMode: SessionMode;
sessionId?: string | null;
}

// We split the CacheKey type into two pieces just for convenience in the code
// below. Note that we don't actually export this type publicly (the
// generateCacheKey hook gets an `unknown` argument).
type CacheKeyData = BaseCacheKeyData & ContextualCacheKeyData;

type GenerateCacheKeyFunction = (
requestContext: GraphQLRequestContext<Record<string, any>>,
keyData: CacheKeyData,
) => string;

interface CacheValue {
// Note: we only store data responses in the cache, not errors.
//
Expand Down Expand Up @@ -161,7 +169,7 @@ export default function plugin(
options.generateCacheKey ?? ((_, key) => sha(JSON.stringify(key)));

let sessionId: string | null = null;
let baseCacheKey: BaseCacheKey | null = null;
let baseCacheKey: BaseCacheKeyData | null = null;
let age: number | null = null;

return {
Expand All @@ -175,7 +183,7 @@ export default function plugin(
}

async function cacheGet(
contextualCacheKeyFields: ContextualCacheKey,
contextualCacheKeyFields: ContextualCacheKeyData,
): Promise<GraphQLResponse | null> {
const cacheKeyData = {
...baseCacheKey!,
Expand Down Expand Up @@ -291,7 +299,7 @@ export default function plugin(
}

const cacheSetInBackground = (
contextualCacheKeyFields: ContextualCacheKey,
contextualCacheKeyFields: ContextualCacheKeyData,
): void => {
const cacheKeyData = {
...baseCacheKey!,
Expand Down