diff --git a/lib/SchemaBuilder.js b/lib/SchemaBuilder.js index 8e6da93..6624265 100644 --- a/lib/SchemaBuilder.js +++ b/lib/SchemaBuilder.js @@ -293,15 +293,15 @@ class SchemaBuilder { throw new Error(`relation type "${relation.constructor.name}" is not supported`) } - async _checkCache(request) { - return await this.cache.getCache(request) || null + async _checkCache(request, requestCacheKey) { + return await this.cache.getCache(request, requestCacheKey) || null } _resolverForModel(modelData, extraQuery) { return async(ctx, ignore1, request, data) => { const cacheKeyElements = { res: JSON.parse(JSON.stringify(request.res || request.body)), ignore1 } - const cached = await this._checkCache(cacheKeyElements) + const cached = await this._checkCache(cacheKeyElements, request.req.requestCacheKey) const skipCache = request?.res?.skipCache ?? request?.body?.skipCache ?? false if (cached && !skipCache) { return cached @@ -345,7 +345,7 @@ class SchemaBuilder { } const result = await builder.then(toJson) - this.cache && result ? await this.cache?.cacheResult(cacheKeyElements, result) : null + this.cache && result ? await this.cache?.cacheResult(cacheKeyElements, result, request.req.requestCacheKey) : null return result } } diff --git a/lib/cache/caching.js b/lib/cache/caching.js index 201b61a..b07b19d 100644 --- a/lib/cache/caching.js +++ b/lib/cache/caching.js @@ -47,22 +47,25 @@ class Cache { this.enabled = true } - generateRedisKey(request) { + generateRedisKey(request, requestCacheKey) { try { const bodyData = request if (!bodyData) return null - return `${this.redisKeyPrefix}_${md5(JSON.stringify(bodyData))}` + + const cacheKey = requestCacheKey ? `_${requestCacheKey}` : '' + + return `${this.redisKeyPrefix}${cacheKey}_${md5(JSON.stringify(bodyData))}` } catch (error) { return null } } - async getCache(request) { - const cacheKey = this.generateRedisKey(request) + async getCache(request, requestCacheKey) { + const cacheKey = this.generateRedisKey(request, requestCacheKey) if (this.enabled && cacheKey) { return new Promise((resolve, reject) => { - this.redisClient.get(this.generateRedisKey(request), (error, value) => { + this.redisClient.get(this.generateRedisKey(request, requestCacheKey), (error, value) => { if (error) return reject(error) if (value) return resolve(JSON.parse(value)) return resolve(null) @@ -71,10 +74,10 @@ class Cache { } } - async cacheResult(request, result) { - const cacheKey = this.generateRedisKey(request) + async cacheResult(request, result, requestCacheKey) { + const cacheKey = this.generateRedisKey(request, requestCacheKey) if (this.enabled && cacheKey) { - await this.redisClient.setex(this.generateRedisKey(request), parseInt(this.timeout), JSON.stringify(result)) + await this.redisClient.setex(this.generateRedisKey(request, requestCacheKey), parseInt(this.timeout), JSON.stringify(result)) } } }