@envelop/response-cache 2.3.3 → 2.3.4-alpha-fae0892.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/index.js CHANGED
@@ -184,8 +184,18 @@ const defaultShouldCacheResult = (params) => {
184
184
  }
185
185
  return true;
186
186
  };
187
+ // @deprecated This will be removed in the next major
187
188
  const defaultGetDocumentStringFromContext = context => context[rawDocumentStringSymbol];
188
- function useResponseCache({ cache = createInMemoryCache(), ttl: globalTtl = Infinity, session = () => null, enabled, ignoredTypes = [], ttlPerType = {}, ttlPerSchemaCoordinate = {}, idFields = ['id'], invalidateViaMutation = true, buildResponseCacheKey = defaultBuildResponseCacheKey, getDocumentStringFromContext = defaultGetDocumentStringFromContext, shouldCacheResult = defaultShouldCacheResult,
189
+ const documentStringByDocument = new WeakMap();
190
+ function getDocumentStringFromDocument(documentNode) {
191
+ let documentString = documentStringByDocument.get(documentNode);
192
+ if (!documentString) {
193
+ documentString = graphql.print(documentNode);
194
+ documentStringByDocument.set(documentNode, documentString);
195
+ }
196
+ return documentString;
197
+ }
198
+ function useResponseCache({ cache = createInMemoryCache(), ttl: globalTtl = Infinity, session = () => null, enabled, ignoredTypes = [], ttlPerType = {}, ttlPerSchemaCoordinate = {}, idFields = ['id'], invalidateViaMutation = true, buildResponseCacheKey = defaultBuildResponseCacheKey, getDocumentStringFromContext, shouldCacheResult = defaultShouldCacheResult,
189
199
  // eslint-disable-next-line dot-notation
190
200
  includeExtensionMetadata = typeof process !== 'undefined' ? process.env['NODE_ENV'] === 'development' : false, } = {}) {
191
201
  const appliedTransform = Symbol('responseCache.appliedTransform');
@@ -206,19 +216,15 @@ includeExtensionMetadata = typeof process !== 'undefined' ? process.env['NODE_EN
206
216
  };
207
217
  replaceSchema(patchedSchema);
208
218
  },
209
- onParse(parseCtx) {
210
- return function onParseEnd(ctx) {
211
- if (ctx.result && 'kind' in ctx.result) {
212
- const source = parseCtx.params.source;
213
- const rawDocumentString = typeof source === 'string' ? source : source.body;
214
- ctx.extendContext({
215
- [rawDocumentStringSymbol]: rawDocumentString,
216
- });
219
+ onParse({ params: { source } }) {
220
+ return function onParseEnd({ result }) {
221
+ if (result != null && !(result instanceof Error)) {
222
+ documentStringByDocument.set(result, source.toString());
217
223
  }
218
224
  };
219
225
  },
220
226
  async onExecute(ctx) {
221
- var _a;
227
+ var _a, _b;
222
228
  const identifier = new Map();
223
229
  const types = new Set();
224
230
  const context = {
@@ -258,98 +264,92 @@ includeExtensionMetadata = typeof process !== 'undefined' ? process.env['NODE_EN
258
264
  },
259
265
  };
260
266
  }
261
- const documentString = getDocumentStringFromContext(ctx.args.contextValue);
262
- if (documentString != null) {
263
- const operationId = await buildResponseCacheKey({
264
- documentString,
265
- variableValues: ctx.args.variableValues,
266
- operationName: ctx.args.operationName,
267
- sessionId: session(ctx.args.contextValue),
268
- });
269
- if (((_a = enabled === null || enabled === void 0 ? void 0 : enabled(ctx.args.contextValue)) !== null && _a !== void 0 ? _a : true) === true) {
270
- const cachedResponse = await cache.get(operationId);
271
- if (cachedResponse != null) {
272
- if (includeExtensionMetadata) {
273
- ctx.setResultAndStopExecution({
274
- ...cachedResponse,
275
- extensions: {
276
- responseCache: {
277
- hit: true,
278
- },
267
+ const documentString = (_a = getDocumentStringFromContext === null || getDocumentStringFromContext === void 0 ? void 0 : getDocumentStringFromContext(ctx.args.contextValue)) !== null && _a !== void 0 ? _a : getDocumentStringFromDocument(ctx.args.document);
268
+ const operationId = await buildResponseCacheKey({
269
+ documentString,
270
+ variableValues: ctx.args.variableValues,
271
+ operationName: ctx.args.operationName,
272
+ sessionId: session(ctx.args.contextValue),
273
+ });
274
+ if (((_b = enabled === null || enabled === void 0 ? void 0 : enabled(ctx.args.contextValue)) !== null && _b !== void 0 ? _b : true) === true) {
275
+ const cachedResponse = await cache.get(operationId);
276
+ if (cachedResponse != null) {
277
+ if (includeExtensionMetadata) {
278
+ ctx.setResultAndStopExecution({
279
+ ...cachedResponse,
280
+ extensions: {
281
+ responseCache: {
282
+ hit: true,
279
283
  },
280
- });
281
- }
282
- else {
283
- ctx.setResultAndStopExecution(cachedResponse);
284
- }
285
- return;
284
+ },
285
+ });
286
286
  }
287
+ else {
288
+ ctx.setResultAndStopExecution(cachedResponse);
289
+ }
290
+ return;
287
291
  }
288
- if (ttlPerSchemaCoordinate) {
289
- const typeInfo = new graphql.TypeInfo(ctx.args.schema);
290
- graphql.visit(ctx.args.document, graphql.visitWithTypeInfo(typeInfo, {
291
- Field(fieldNode) {
292
- const parentType = typeInfo.getParentType();
293
- if (parentType) {
294
- const schemaCoordinate = `${parentType.name}.${fieldNode.name.value}`;
295
- const maybeTtl = ttlPerSchemaCoordinate[schemaCoordinate];
296
- if (maybeTtl !== undefined) {
297
- context.currentTtl = calculateTtl(maybeTtl, context.currentTtl);
298
- }
299
- }
300
- },
301
- }));
302
- }
303
- return {
304
- onExecuteDone({ result, setResult }) {
305
- var _a;
306
- if (core.isAsyncIterable(result)) {
307
- // eslint-disable-next-line no-console
308
- console.warn('[useResponseCache] AsyncIterable returned from execute is currently unsupported.');
309
- return;
310
- }
311
- if (context.skip) {
312
- return;
313
- }
314
- if (!shouldCacheResult({ result })) {
315
- return;
316
- }
317
- // we only use the global ttl if no currentTtl has been determined.
318
- const finalTtl = (_a = context.currentTtl) !== null && _a !== void 0 ? _a : globalTtl;
319
- if (finalTtl === 0) {
320
- if (includeExtensionMetadata) {
321
- setResult({
322
- ...result,
323
- extensions: {
324
- responseCache: {
325
- hit: false,
326
- didCache: false,
327
- },
328
- },
329
- });
292
+ }
293
+ if (ttlPerSchemaCoordinate) {
294
+ const typeInfo = new graphql.TypeInfo(ctx.args.schema);
295
+ graphql.visit(ctx.args.document, graphql.visitWithTypeInfo(typeInfo, {
296
+ Field(fieldNode) {
297
+ const parentType = typeInfo.getParentType();
298
+ if (parentType) {
299
+ const schemaCoordinate = `${parentType.name}.${fieldNode.name.value}`;
300
+ const maybeTtl = ttlPerSchemaCoordinate[schemaCoordinate];
301
+ if (maybeTtl !== undefined) {
302
+ context.currentTtl = calculateTtl(maybeTtl, context.currentTtl);
330
303
  }
331
- return;
332
304
  }
333
- cache.set(operationId, result, identifier.values(), finalTtl);
305
+ },
306
+ }));
307
+ }
308
+ return {
309
+ onExecuteDone({ result, setResult }) {
310
+ var _a;
311
+ if (core.isAsyncIterable(result)) {
312
+ // eslint-disable-next-line no-console
313
+ console.warn('[useResponseCache] AsyncIterable returned from execute is currently unsupported.');
314
+ return;
315
+ }
316
+ if (context.skip) {
317
+ return;
318
+ }
319
+ if (!shouldCacheResult({ result })) {
320
+ return;
321
+ }
322
+ // we only use the global ttl if no currentTtl has been determined.
323
+ const finalTtl = (_a = context.currentTtl) !== null && _a !== void 0 ? _a : globalTtl;
324
+ if (finalTtl === 0) {
334
325
  if (includeExtensionMetadata) {
335
326
  setResult({
336
327
  ...result,
337
328
  extensions: {
338
329
  responseCache: {
339
330
  hit: false,
340
- didCache: true,
341
- ttl: finalTtl,
331
+ didCache: false,
342
332
  },
343
333
  },
344
334
  });
345
335
  }
346
- },
347
- };
348
- }
349
- // eslint-disable-next-line no-console
350
- console.warn(`[useResponseCache] Failed extracting document string from the context. The response will not be cached or served from the cache. ` +
351
- `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.`);
352
- return undefined;
336
+ return;
337
+ }
338
+ cache.set(operationId, result, identifier.values(), finalTtl);
339
+ if (includeExtensionMetadata) {
340
+ setResult({
341
+ ...result,
342
+ extensions: {
343
+ responseCache: {
344
+ hit: false,
345
+ didCache: true,
346
+ ttl: finalTtl,
347
+ },
348
+ },
349
+ });
350
+ }
351
+ },
352
+ };
353
353
  },
354
354
  };
355
355
  }
package/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import LRU from 'lru-cache';
2
2
  import { isAsyncIterable } from '@envelop/core';
3
3
  import { mapSchema, MapperKind } from '@graphql-tools/utils';
4
- import { defaultFieldResolver, TypeInfo, visit, visitWithTypeInfo } from 'graphql';
4
+ import { defaultFieldResolver, TypeInfo, visit, visitWithTypeInfo, print } from 'graphql';
5
5
  import jsonStableStringify from 'fast-json-stable-stringify';
6
6
 
7
7
  const createInMemoryCache = (params) => {
@@ -178,8 +178,18 @@ const defaultShouldCacheResult = (params) => {
178
178
  }
179
179
  return true;
180
180
  };
181
+ // @deprecated This will be removed in the next major
181
182
  const defaultGetDocumentStringFromContext = context => context[rawDocumentStringSymbol];
182
- function useResponseCache({ cache = createInMemoryCache(), ttl: globalTtl = Infinity, session = () => null, enabled, ignoredTypes = [], ttlPerType = {}, ttlPerSchemaCoordinate = {}, idFields = ['id'], invalidateViaMutation = true, buildResponseCacheKey = defaultBuildResponseCacheKey, getDocumentStringFromContext = defaultGetDocumentStringFromContext, shouldCacheResult = defaultShouldCacheResult,
183
+ const documentStringByDocument = new WeakMap();
184
+ function getDocumentStringFromDocument(documentNode) {
185
+ let documentString = documentStringByDocument.get(documentNode);
186
+ if (!documentString) {
187
+ documentString = print(documentNode);
188
+ documentStringByDocument.set(documentNode, documentString);
189
+ }
190
+ return documentString;
191
+ }
192
+ function useResponseCache({ cache = createInMemoryCache(), ttl: globalTtl = Infinity, session = () => null, enabled, ignoredTypes = [], ttlPerType = {}, ttlPerSchemaCoordinate = {}, idFields = ['id'], invalidateViaMutation = true, buildResponseCacheKey = defaultBuildResponseCacheKey, getDocumentStringFromContext, shouldCacheResult = defaultShouldCacheResult,
183
193
  // eslint-disable-next-line dot-notation
184
194
  includeExtensionMetadata = typeof process !== 'undefined' ? process.env['NODE_ENV'] === 'development' : false, } = {}) {
185
195
  const appliedTransform = Symbol('responseCache.appliedTransform');
@@ -200,19 +210,15 @@ includeExtensionMetadata = typeof process !== 'undefined' ? process.env['NODE_EN
200
210
  };
201
211
  replaceSchema(patchedSchema);
202
212
  },
203
- onParse(parseCtx) {
204
- return function onParseEnd(ctx) {
205
- if (ctx.result && 'kind' in ctx.result) {
206
- const source = parseCtx.params.source;
207
- const rawDocumentString = typeof source === 'string' ? source : source.body;
208
- ctx.extendContext({
209
- [rawDocumentStringSymbol]: rawDocumentString,
210
- });
213
+ onParse({ params: { source } }) {
214
+ return function onParseEnd({ result }) {
215
+ if (result != null && !(result instanceof Error)) {
216
+ documentStringByDocument.set(result, source.toString());
211
217
  }
212
218
  };
213
219
  },
214
220
  async onExecute(ctx) {
215
- var _a;
221
+ var _a, _b;
216
222
  const identifier = new Map();
217
223
  const types = new Set();
218
224
  const context = {
@@ -252,98 +258,92 @@ includeExtensionMetadata = typeof process !== 'undefined' ? process.env['NODE_EN
252
258
  },
253
259
  };
254
260
  }
255
- const documentString = getDocumentStringFromContext(ctx.args.contextValue);
256
- if (documentString != null) {
257
- const operationId = await buildResponseCacheKey({
258
- documentString,
259
- variableValues: ctx.args.variableValues,
260
- operationName: ctx.args.operationName,
261
- sessionId: session(ctx.args.contextValue),
262
- });
263
- if (((_a = enabled === null || enabled === void 0 ? void 0 : enabled(ctx.args.contextValue)) !== null && _a !== void 0 ? _a : true) === true) {
264
- const cachedResponse = await cache.get(operationId);
265
- if (cachedResponse != null) {
266
- if (includeExtensionMetadata) {
267
- ctx.setResultAndStopExecution({
268
- ...cachedResponse,
269
- extensions: {
270
- responseCache: {
271
- hit: true,
272
- },
261
+ const documentString = (_a = getDocumentStringFromContext === null || getDocumentStringFromContext === void 0 ? void 0 : getDocumentStringFromContext(ctx.args.contextValue)) !== null && _a !== void 0 ? _a : getDocumentStringFromDocument(ctx.args.document);
262
+ const operationId = await buildResponseCacheKey({
263
+ documentString,
264
+ variableValues: ctx.args.variableValues,
265
+ operationName: ctx.args.operationName,
266
+ sessionId: session(ctx.args.contextValue),
267
+ });
268
+ if (((_b = enabled === null || enabled === void 0 ? void 0 : enabled(ctx.args.contextValue)) !== null && _b !== void 0 ? _b : true) === true) {
269
+ const cachedResponse = await cache.get(operationId);
270
+ if (cachedResponse != null) {
271
+ if (includeExtensionMetadata) {
272
+ ctx.setResultAndStopExecution({
273
+ ...cachedResponse,
274
+ extensions: {
275
+ responseCache: {
276
+ hit: true,
273
277
  },
274
- });
275
- }
276
- else {
277
- ctx.setResultAndStopExecution(cachedResponse);
278
- }
279
- return;
278
+ },
279
+ });
280
280
  }
281
+ else {
282
+ ctx.setResultAndStopExecution(cachedResponse);
283
+ }
284
+ return;
281
285
  }
282
- if (ttlPerSchemaCoordinate) {
283
- const typeInfo = new TypeInfo(ctx.args.schema);
284
- visit(ctx.args.document, visitWithTypeInfo(typeInfo, {
285
- Field(fieldNode) {
286
- const parentType = typeInfo.getParentType();
287
- if (parentType) {
288
- const schemaCoordinate = `${parentType.name}.${fieldNode.name.value}`;
289
- const maybeTtl = ttlPerSchemaCoordinate[schemaCoordinate];
290
- if (maybeTtl !== undefined) {
291
- context.currentTtl = calculateTtl(maybeTtl, context.currentTtl);
292
- }
293
- }
294
- },
295
- }));
296
- }
297
- return {
298
- onExecuteDone({ result, setResult }) {
299
- var _a;
300
- if (isAsyncIterable(result)) {
301
- // eslint-disable-next-line no-console
302
- console.warn('[useResponseCache] AsyncIterable returned from execute is currently unsupported.');
303
- return;
304
- }
305
- if (context.skip) {
306
- return;
307
- }
308
- if (!shouldCacheResult({ result })) {
309
- return;
310
- }
311
- // we only use the global ttl if no currentTtl has been determined.
312
- const finalTtl = (_a = context.currentTtl) !== null && _a !== void 0 ? _a : globalTtl;
313
- if (finalTtl === 0) {
314
- if (includeExtensionMetadata) {
315
- setResult({
316
- ...result,
317
- extensions: {
318
- responseCache: {
319
- hit: false,
320
- didCache: false,
321
- },
322
- },
323
- });
286
+ }
287
+ if (ttlPerSchemaCoordinate) {
288
+ const typeInfo = new TypeInfo(ctx.args.schema);
289
+ visit(ctx.args.document, visitWithTypeInfo(typeInfo, {
290
+ Field(fieldNode) {
291
+ const parentType = typeInfo.getParentType();
292
+ if (parentType) {
293
+ const schemaCoordinate = `${parentType.name}.${fieldNode.name.value}`;
294
+ const maybeTtl = ttlPerSchemaCoordinate[schemaCoordinate];
295
+ if (maybeTtl !== undefined) {
296
+ context.currentTtl = calculateTtl(maybeTtl, context.currentTtl);
324
297
  }
325
- return;
326
298
  }
327
- cache.set(operationId, result, identifier.values(), finalTtl);
299
+ },
300
+ }));
301
+ }
302
+ return {
303
+ onExecuteDone({ result, setResult }) {
304
+ var _a;
305
+ if (isAsyncIterable(result)) {
306
+ // eslint-disable-next-line no-console
307
+ console.warn('[useResponseCache] AsyncIterable returned from execute is currently unsupported.');
308
+ return;
309
+ }
310
+ if (context.skip) {
311
+ return;
312
+ }
313
+ if (!shouldCacheResult({ result })) {
314
+ return;
315
+ }
316
+ // we only use the global ttl if no currentTtl has been determined.
317
+ const finalTtl = (_a = context.currentTtl) !== null && _a !== void 0 ? _a : globalTtl;
318
+ if (finalTtl === 0) {
328
319
  if (includeExtensionMetadata) {
329
320
  setResult({
330
321
  ...result,
331
322
  extensions: {
332
323
  responseCache: {
333
324
  hit: false,
334
- didCache: true,
335
- ttl: finalTtl,
325
+ didCache: false,
336
326
  },
337
327
  },
338
328
  });
339
329
  }
340
- },
341
- };
342
- }
343
- // eslint-disable-next-line no-console
344
- console.warn(`[useResponseCache] Failed extracting document string from the context. The response will not be cached or served from the cache. ` +
345
- `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.`);
346
- return undefined;
330
+ return;
331
+ }
332
+ cache.set(operationId, result, identifier.values(), finalTtl);
333
+ if (includeExtensionMetadata) {
334
+ setResult({
335
+ ...result,
336
+ extensions: {
337
+ responseCache: {
338
+ hit: false,
339
+ didCache: true,
340
+ ttl: finalTtl,
341
+ },
342
+ },
343
+ });
344
+ }
345
+ },
346
+ };
347
347
  },
348
348
  };
349
349
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@envelop/response-cache",
3
- "version": "2.3.3",
3
+ "version": "2.3.4-alpha-fae0892.0",
4
4
  "sideEffects": false,
5
5
  "peerDependencies": {
6
6
  "@envelop/core": "^2.3.3",
package/plugin.d.ts CHANGED
@@ -76,6 +76,8 @@ export declare type UseResponseCacheParameter<C = any> = {
76
76
  * By default, the useResponseCache plugin hooks into onParse and writes the original operation string to the context.
77
77
  * If you are hard overriding parse you need to set this function, otherwise responses will not be cached or served from the cache.
78
78
  * Defaults to `defaultGetDocumentStringFromContext`
79
+ *
80
+ * @deprecated No longer being used in the next major version.
79
81
  */
80
82
  getDocumentStringFromContext?: GetDocumentStringFromContextFunction;
81
83
  /**