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