@envelop/response-cache 2.4.0-alpha-db79afa.0 → 2.4.0-alpha-05dbec7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cjs/cache.js +2 -0
- package/cjs/hashSHA256.js +66 -0
- package/cjs/in-memory-cache.js +86 -0
- package/cjs/index.js +6 -0
- package/cjs/package.json +1 -0
- package/cjs/plugin.js +270 -0
- package/esm/cache.js +1 -0
- package/esm/hashSHA256.js +62 -0
- package/esm/in-memory-cache.js +80 -0
- package/esm/index.js +3 -0
- package/esm/plugin.js +262 -0
- package/package.json +35 -14
- package/{cache.d.ts → typings/cache.d.ts} +0 -0
- package/{hashSHA256.d.ts → typings/hashSHA256.d.ts} +0 -0
- package/{in-memory-cache.d.ts → typings/in-memory-cache.d.ts} +2 -2
- package/typings/index.d.ts +3 -0
- package/{plugin.d.ts → typings/plugin.d.ts} +1 -1
- package/README.md +0 -491
- package/index.d.ts +0 -3
- package/index.js +0 -422
- package/index.mjs +0 -411
package/esm/plugin.js
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { isAsyncIterable } from '@envelop/core';
|
|
2
|
+
import { MapperKind, mapSchema } from '@graphql-tools/utils';
|
|
3
|
+
import { visit, TypeInfo, visitWithTypeInfo, defaultFieldResolver, } from 'graphql';
|
|
4
|
+
import jsonStableStringify from 'fast-json-stable-stringify';
|
|
5
|
+
import { createInMemoryCache } from './in-memory-cache.js';
|
|
6
|
+
import { hashSHA256 } from './hashSHA256.js';
|
|
7
|
+
const contextSymbol = Symbol('responseCache');
|
|
8
|
+
const rawDocumentStringSymbol = Symbol('rawDocumentString');
|
|
9
|
+
/**
|
|
10
|
+
* Default function used for building the response cache key.
|
|
11
|
+
* It is exported here for advanced use-cases. E.g. if you want to short circuit and serve responses from the cache on a global level in order to completely by-pass the GraphQL flow.
|
|
12
|
+
*/
|
|
13
|
+
export const defaultBuildResponseCacheKey = params => {
|
|
14
|
+
var _a, _b, _c;
|
|
15
|
+
return hashSHA256([
|
|
16
|
+
params.documentString,
|
|
17
|
+
(_a = params.operationName) !== null && _a !== void 0 ? _a : '',
|
|
18
|
+
jsonStableStringify((_b = params.variableValues) !== null && _b !== void 0 ? _b : {}),
|
|
19
|
+
(_c = params.sessionId) !== null && _c !== void 0 ? _c : '',
|
|
20
|
+
].join('|'));
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Default function used to check if the result should be cached.
|
|
24
|
+
*
|
|
25
|
+
* It is exported here for advanced use-cases. E.g. if you want to choose if
|
|
26
|
+
* results with certain error types should be cached.
|
|
27
|
+
*
|
|
28
|
+
* By default, results with errors (unexpected, EnvelopError, or GraphQLError) are not cached.
|
|
29
|
+
*/
|
|
30
|
+
export const defaultShouldCacheResult = (params) => {
|
|
31
|
+
if (params.result.errors) {
|
|
32
|
+
// eslint-disable-next-line no-console
|
|
33
|
+
console.warn('[useResponseCache] Failed to cache due to errors');
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
};
|
|
38
|
+
export const defaultGetDocumentStringFromContext = context => context[rawDocumentStringSymbol];
|
|
39
|
+
export function useResponseCache({ cache = createInMemoryCache(), ttl: globalTtl = Infinity, session = () => null, enabled, ignoredTypes = [], ttlPerType = {}, ttlPerSchemaCoordinate = {}, idFields = ['id'], invalidateViaMutation = true, buildResponseCacheKey = defaultBuildResponseCacheKey, getDocumentStringFromContext = defaultGetDocumentStringFromContext, shouldCacheResult = defaultShouldCacheResult,
|
|
40
|
+
// eslint-disable-next-line dot-notation
|
|
41
|
+
includeExtensionMetadata = typeof process !== 'undefined' ? process.env['NODE_ENV'] === 'development' : false, } = {}) {
|
|
42
|
+
const appliedTransform = Symbol('responseCache.appliedTransform');
|
|
43
|
+
const ignoredTypesMap = new Set(ignoredTypes);
|
|
44
|
+
// never cache Introspections
|
|
45
|
+
ttlPerSchemaCoordinate = { 'Query.__schema': 0, ...ttlPerSchemaCoordinate };
|
|
46
|
+
return {
|
|
47
|
+
onSchemaChange({ schema, replaceSchema }) {
|
|
48
|
+
var _a;
|
|
49
|
+
// @ts-expect-error See https://github.com/graphql/graphql-js/pull/3511 - remove this comments once merged
|
|
50
|
+
if (((_a = schema.extensions) === null || _a === void 0 ? void 0 : _a[appliedTransform]) === true) {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const patchedSchema = applyResponseCacheLogic(schema, idFields);
|
|
54
|
+
patchedSchema.extensions = {
|
|
55
|
+
...patchedSchema.extensions,
|
|
56
|
+
[appliedTransform]: true,
|
|
57
|
+
};
|
|
58
|
+
replaceSchema(patchedSchema);
|
|
59
|
+
},
|
|
60
|
+
onParse(parseCtx) {
|
|
61
|
+
return function onParseEnd(ctx) {
|
|
62
|
+
if (ctx.result && 'kind' in ctx.result) {
|
|
63
|
+
const source = parseCtx.params.source;
|
|
64
|
+
const rawDocumentString = typeof source === 'string' ? source : source.body;
|
|
65
|
+
ctx.extendContext({
|
|
66
|
+
[rawDocumentStringSymbol]: rawDocumentString,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
},
|
|
71
|
+
async onExecute(ctx) {
|
|
72
|
+
var _a;
|
|
73
|
+
const identifier = new Map();
|
|
74
|
+
const types = new Set();
|
|
75
|
+
const context = {
|
|
76
|
+
identifier,
|
|
77
|
+
types,
|
|
78
|
+
currentTtl: undefined,
|
|
79
|
+
ttlPerType,
|
|
80
|
+
ignoredTypesMap,
|
|
81
|
+
skip: false,
|
|
82
|
+
};
|
|
83
|
+
ctx.extendContext({
|
|
84
|
+
[contextSymbol]: context,
|
|
85
|
+
});
|
|
86
|
+
if (isMutation(ctx.args.document)) {
|
|
87
|
+
if (invalidateViaMutation === false) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
onExecuteDone({ result, setResult }) {
|
|
92
|
+
if (isAsyncIterable(result)) {
|
|
93
|
+
// eslint-disable-next-line no-console
|
|
94
|
+
console.warn('[useResponseCache] AsyncIterable returned from execute is currently unsupported.');
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
cache.invalidate(context.identifier.values());
|
|
98
|
+
if (includeExtensionMetadata) {
|
|
99
|
+
setResult({
|
|
100
|
+
...result,
|
|
101
|
+
extensions: {
|
|
102
|
+
...result.extensions,
|
|
103
|
+
responseCache: {
|
|
104
|
+
invalidatedEntities: Array.from(context.identifier.values()),
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const documentString = getDocumentStringFromContext(ctx.args.contextValue);
|
|
113
|
+
if (documentString != null) {
|
|
114
|
+
const operationId = await buildResponseCacheKey({
|
|
115
|
+
documentString,
|
|
116
|
+
variableValues: ctx.args.variableValues,
|
|
117
|
+
operationName: ctx.args.operationName,
|
|
118
|
+
sessionId: session(ctx.args.contextValue),
|
|
119
|
+
});
|
|
120
|
+
if (((_a = enabled === null || enabled === void 0 ? void 0 : enabled(ctx.args.contextValue)) !== null && _a !== void 0 ? _a : true) === true) {
|
|
121
|
+
const cachedResponse = await cache.get(operationId);
|
|
122
|
+
if (cachedResponse != null) {
|
|
123
|
+
if (includeExtensionMetadata) {
|
|
124
|
+
ctx.setResultAndStopExecution({
|
|
125
|
+
...cachedResponse,
|
|
126
|
+
extensions: {
|
|
127
|
+
responseCache: {
|
|
128
|
+
hit: true,
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
ctx.setResultAndStopExecution(cachedResponse);
|
|
135
|
+
}
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (ttlPerSchemaCoordinate) {
|
|
140
|
+
const typeInfo = new TypeInfo(ctx.args.schema);
|
|
141
|
+
visit(ctx.args.document, visitWithTypeInfo(typeInfo, {
|
|
142
|
+
Field(fieldNode) {
|
|
143
|
+
const parentType = typeInfo.getParentType();
|
|
144
|
+
if (parentType) {
|
|
145
|
+
const schemaCoordinate = `${parentType.name}.${fieldNode.name.value}`;
|
|
146
|
+
const maybeTtl = ttlPerSchemaCoordinate[schemaCoordinate];
|
|
147
|
+
if (maybeTtl !== undefined) {
|
|
148
|
+
context.currentTtl = calculateTtl(maybeTtl, context.currentTtl);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
onExecuteDone({ result, setResult }) {
|
|
156
|
+
var _a;
|
|
157
|
+
if (isAsyncIterable(result)) {
|
|
158
|
+
// eslint-disable-next-line no-console
|
|
159
|
+
console.warn('[useResponseCache] AsyncIterable returned from execute is currently unsupported.');
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (context.skip) {
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (!shouldCacheResult({ result })) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
// we only use the global ttl if no currentTtl has been determined.
|
|
169
|
+
const finalTtl = (_a = context.currentTtl) !== null && _a !== void 0 ? _a : globalTtl;
|
|
170
|
+
if (finalTtl === 0) {
|
|
171
|
+
if (includeExtensionMetadata) {
|
|
172
|
+
setResult({
|
|
173
|
+
...result,
|
|
174
|
+
extensions: {
|
|
175
|
+
responseCache: {
|
|
176
|
+
hit: false,
|
|
177
|
+
didCache: false,
|
|
178
|
+
},
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
cache.set(operationId, result, identifier.values(), finalTtl);
|
|
185
|
+
if (includeExtensionMetadata) {
|
|
186
|
+
setResult({
|
|
187
|
+
...result,
|
|
188
|
+
extensions: {
|
|
189
|
+
responseCache: {
|
|
190
|
+
hit: false,
|
|
191
|
+
didCache: true,
|
|
192
|
+
ttl: finalTtl,
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
// eslint-disable-next-line no-console
|
|
201
|
+
console.warn(`[useResponseCache] Failed extracting document string from the context. The response will not be cached or served from the cache. ` +
|
|
202
|
+
`If you are overriding the 'parse' behavior make sure to pass a custom 'getDocumentStringFromContext' function for getting the document string, which is required for building the response cache key.`);
|
|
203
|
+
return undefined;
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
function isOperationDefinition(node) {
|
|
208
|
+
return (node === null || node === void 0 ? void 0 : node.kind) === 'OperationDefinition';
|
|
209
|
+
}
|
|
210
|
+
function calculateTtl(typeTtl, currentTtl) {
|
|
211
|
+
if (typeof currentTtl === 'number') {
|
|
212
|
+
return Math.min(currentTtl, typeTtl);
|
|
213
|
+
}
|
|
214
|
+
return typeTtl;
|
|
215
|
+
}
|
|
216
|
+
function isMutation(doc) {
|
|
217
|
+
return doc.definitions.find(isOperationDefinition).operation === 'mutation';
|
|
218
|
+
}
|
|
219
|
+
function runWith(input, callback) {
|
|
220
|
+
if (input instanceof Promise) {
|
|
221
|
+
input.then(callback, () => undefined);
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
callback(input);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function applyResponseCacheLogic(schema, idFieldNames) {
|
|
228
|
+
return mapSchema(schema, {
|
|
229
|
+
[MapperKind.OBJECT_FIELD](fieldConfig, fieldName, typename) {
|
|
230
|
+
if (idFieldNames.includes(fieldName)) {
|
|
231
|
+
return {
|
|
232
|
+
...fieldConfig,
|
|
233
|
+
resolve(src, args, context, info) {
|
|
234
|
+
var _a;
|
|
235
|
+
const result = ((_a = fieldConfig.resolve) !== null && _a !== void 0 ? _a : defaultFieldResolver)(src, args, context, info);
|
|
236
|
+
runWith(result, (id) => {
|
|
237
|
+
const ctx = context[contextSymbol];
|
|
238
|
+
if (ctx !== undefined) {
|
|
239
|
+
if (ctx.ignoredTypesMap.has(typename)) {
|
|
240
|
+
ctx.skip = true;
|
|
241
|
+
}
|
|
242
|
+
if (ctx.skip === true) {
|
|
243
|
+
ctx.skip = true;
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
247
|
+
// @ts-ignore TODO: investigate what to do if id is something unexpected
|
|
248
|
+
ctx.identifier.set(`${typename}:${id}`, { typename, id });
|
|
249
|
+
ctx.types.add(typename);
|
|
250
|
+
if (typename in ctx.ttlPerType) {
|
|
251
|
+
ctx.currentTtl = calculateTtl(ctx.ttlPerType[typename], ctx.currentTtl);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
return result;
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
return fieldConfig;
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
}
|
package/package.json
CHANGED
|
@@ -1,38 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@envelop/response-cache",
|
|
3
|
-
"version": "2.4.0-alpha-
|
|
3
|
+
"version": "2.4.0-alpha-05dbec7.0",
|
|
4
4
|
"sideEffects": false,
|
|
5
5
|
"peerDependencies": {
|
|
6
|
-
"@envelop/core": "2.4.0-alpha-
|
|
6
|
+
"@envelop/core": "2.4.0-alpha-05dbec7.0",
|
|
7
7
|
"graphql": "^14.0.0 || ^15.0.0 || ^16.0.0"
|
|
8
8
|
},
|
|
9
9
|
"dependencies": {
|
|
10
10
|
"@graphql-tools/utils": "^8.6.1",
|
|
11
|
-
"
|
|
12
|
-
"
|
|
11
|
+
"lru-cache": "^6.0.0",
|
|
12
|
+
"fast-json-stable-stringify": "^2.1.0"
|
|
13
13
|
},
|
|
14
14
|
"repository": {
|
|
15
15
|
"type": "git",
|
|
16
|
-
"url": "https://github.com/
|
|
16
|
+
"url": "https://github.com/n1ru4l/envelop.git",
|
|
17
17
|
"directory": "packages/plugins/response-cache"
|
|
18
18
|
},
|
|
19
19
|
"author": "Kamil Kisiela <kamilkisiela@gmail.com>",
|
|
20
20
|
"license": "MIT",
|
|
21
|
-
"main": "index.js",
|
|
22
|
-
"module": "index.
|
|
23
|
-
"typings": "index.d.ts",
|
|
21
|
+
"main": "cjs/index.js",
|
|
22
|
+
"module": "esm/index.js",
|
|
23
|
+
"typings": "typings/index.d.ts",
|
|
24
24
|
"typescript": {
|
|
25
|
-
"definition": "index.d.ts"
|
|
25
|
+
"definition": "typings/index.d.ts"
|
|
26
26
|
},
|
|
27
|
+
"type": "module",
|
|
27
28
|
"exports": {
|
|
28
29
|
".": {
|
|
29
|
-
"require":
|
|
30
|
-
|
|
30
|
+
"require": {
|
|
31
|
+
"types": "./typings/index.d.ts",
|
|
32
|
+
"default": "./cjs/index.js"
|
|
33
|
+
},
|
|
34
|
+
"import": {
|
|
35
|
+
"types": "./typings/index.d.ts",
|
|
36
|
+
"default": "./esm/index.js"
|
|
37
|
+
},
|
|
38
|
+
"default": {
|
|
39
|
+
"types": "./typings/index.d.ts",
|
|
40
|
+
"default": "./esm/index.js"
|
|
41
|
+
}
|
|
31
42
|
},
|
|
32
43
|
"./*": {
|
|
33
|
-
"require":
|
|
34
|
-
|
|
44
|
+
"require": {
|
|
45
|
+
"types": "./typings/*.d.ts",
|
|
46
|
+
"default": "./cjs/*.js"
|
|
47
|
+
},
|
|
48
|
+
"import": {
|
|
49
|
+
"types": "./typings/*.d.ts",
|
|
50
|
+
"default": "./esm/*.js"
|
|
51
|
+
},
|
|
52
|
+
"default": {
|
|
53
|
+
"types": "./typings/*.d.ts",
|
|
54
|
+
"default": "./esm/*.js"
|
|
55
|
+
}
|
|
35
56
|
},
|
|
36
57
|
"./package.json": "./package.json"
|
|
37
58
|
}
|
|
38
|
-
}
|
|
59
|
+
}
|
|
File without changes
|
|
File without changes
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Cache } from './cache';
|
|
1
|
+
import type { Cache } from './cache.js';
|
|
2
2
|
export declare type BuildEntityId = (typename: string, id: number | string) => string;
|
|
3
3
|
export declare type InMemoryCacheParameter = {
|
|
4
4
|
/**
|
|
@@ -11,5 +11,5 @@ export declare type InMemoryCacheParameter = {
|
|
|
11
11
|
*/
|
|
12
12
|
buildEntityId?: BuildEntityId;
|
|
13
13
|
};
|
|
14
|
-
export declare const createInMemoryCache: (params?: InMemoryCacheParameter
|
|
14
|
+
export declare const createInMemoryCache: (params?: InMemoryCacheParameter) => Cache;
|
|
15
15
|
export declare const defaultBuildEntityId: BuildEntityId;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Plugin, Maybe, DefaultContext } from '@envelop/core';
|
|
2
2
|
import { ExecutionArgs, ExecutionResult } from 'graphql';
|
|
3
|
-
import type { Cache } from './cache';
|
|
3
|
+
import type { Cache } from './cache.js';
|
|
4
4
|
/**
|
|
5
5
|
* Function for building the response cache key based on the input parameters
|
|
6
6
|
*/
|