import type { BuildCache, Path, SchemaTypes } from '@pothos/core'; import { type GraphQLOutputType, type GraphQLResolveInfo, getNullableType, isListType, } from 'graphql'; import CacheNode from './cache-node.js'; import type SubscriptionManager from './manager/index.js'; function normalizeListValue(type: GraphQLOutputType, value: unknown) { if (!isListType(getNullableType(type)) || Array.isArray(value)) { return value; } if ( typeof value === 'object' && value !== null && typeof (value as Iterable)[Symbol.iterator] === 'function' ) { return [...(value as Iterable)]; } return value; } export default class SubscriptionCache { manager: SubscriptionManager; buildCache: BuildCache; currentCache = new Map>(); nextCache = new Map>(); invalidPaths: string[] = []; prevInvalidPaths: string[] = []; constructor(manager: SubscriptionManager, buildCache: BuildCache) { this.manager = manager; this.buildCache = buildCache; } get(path: string, reRegister: boolean) { const node = this.currentCache.get(path); if (!node) { return null; } for (const invalid of this.prevInvalidPaths) { if (path.startsWith(invalid)) { return null; } } if (reRegister) { this.nextCache.set(path, node); node.reRegister(); } return node; } getTypeSubscriber(type: string) { const config = this.buildCache.getTypeConfig(type, 'Object'); if (config.graphqlKind === 'Object') { return config.pothosOptions.subscribe ?? null; } return null; } getParent(info: GraphQLResolveInfo): CacheNode | null { let parentPath = info.path.prev; if (!parentPath) { return null; } if (typeof parentPath.key === 'number') { parentPath = parentPath.prev!; } const parentKey = this.cacheKey(parentPath); if (this.nextCache.has(parentKey)) { return this.nextCache.get(parentKey)!; } return null; } managerForParentType(info: GraphQLResolveInfo) { const parentPath = info.path.prev; if (!parentPath) { return null; } const isListItem = typeof parentPath.key === 'number'; const parentKey = this.cacheKey(isListItem ? parentPath.prev! : parentPath); const parentCacheNode = this.nextCache.get(parentKey); return parentCacheNode?.managerForType(parentPath.key) ?? null; } add(info: GraphQLResolveInfo, path: string, canRefetch: boolean, value: unknown) { const parent = this.getParent(info); const node = new CacheNode( this, path, normalizeListValue(info.returnType, value), canRefetch || !parent ? () => { this.invalidPaths.push(path); } : parent.refetch, ); this.nextCache.set(path, node); return node; } next() { this.prevInvalidPaths = this.invalidPaths; this.invalidPaths = []; this.currentCache = this.nextCache; this.nextCache = new Map>(); } cacheKey(path: Path) { let { key, prev } = path; while (prev) { key = `${prev.key}.${key}`; prev = prev.prev; } return key.toString(); } } export { default as CacheNode } from './cache-node.js';