@envelop/persisted-operations 4.4.0-alpha-c0cc559.0 → 4.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/cjs/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./types.js"), exports);
5
+ tslib_1.__exportStar(require("./utils.js"), exports);
6
+ tslib_1.__exportStar(require("./stores/aggregated-store.js"), exports);
7
+ tslib_1.__exportStar(require("./stores/inmemory-store.js"), exports);
8
+ tslib_1.__exportStar(require("./stores/json-file-store.js"), exports);
9
+ tslib_1.__exportStar(require("./plugin.js"), exports);
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
package/cjs/plugin.js ADDED
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.usePersistedOperations = exports.readOperationId = void 0;
4
+ const graphql_1 = require("graphql");
5
+ const utils_js_1 = require("./utils.js");
6
+ const DEFAULT_OPTIONS = {
7
+ onlyPersisted: false,
8
+ };
9
+ const contextProperty = Symbol('persistedOperationId');
10
+ function readOperationId(context) {
11
+ return context[contextProperty];
12
+ }
13
+ exports.readOperationId = readOperationId;
14
+ const usePersistedOperations = (rawOptions) => {
15
+ const options = {
16
+ ...DEFAULT_OPTIONS,
17
+ ...(rawOptions || {}),
18
+ };
19
+ return {
20
+ onParse({ context, params, extendContext, setParsedDocument }) {
21
+ const operationId = options.extractOperationId ? options.extractOperationId(context) : (0, utils_js_1.operationIdFromSource)(params.source);
22
+ if (!operationId) {
23
+ if (options.onlyPersisted) {
24
+ throw new graphql_1.GraphQLError('Must provide operation id');
25
+ }
26
+ return;
27
+ }
28
+ const store = typeof options.store === 'function' ? options.store(context) : options.store;
29
+ if (!store) {
30
+ throw new graphql_1.GraphQLError('Must provide store for persisted-operations!');
31
+ }
32
+ const rawResult = store.get(operationId);
33
+ if (rawResult) {
34
+ const document = typeof rawResult === 'string' ? (0, graphql_1.parse)(rawResult) : rawResult;
35
+ extendContext({ [contextProperty]: operationId });
36
+ setParsedDocument(document);
37
+ return;
38
+ }
39
+ if (options.onMissingMatch)
40
+ options.onMissingMatch(context, operationId);
41
+ if (options.onlyPersisted) {
42
+ // we want to throw an error only when "onlyPersisted" is true, otherwise we let execution continue normally
43
+ throw new graphql_1.GraphQLError(`Unable to match operation with id '${operationId}'`);
44
+ }
45
+ // if we reach this stage we could not retrieve a persisted operation and we didn't throw any error as onlyPersisted is false
46
+ // hence we let operation continue assuming consumer is not passing an operation id, but a plain query string, with current request.
47
+ },
48
+ };
49
+ };
50
+ exports.usePersistedOperations = usePersistedOperations;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AggregatedStore = void 0;
4
+ class AggregatedStore {
5
+ constructor(stores) {
6
+ this.stores = stores;
7
+ }
8
+ get(operationId) {
9
+ for (const store of this.stores) {
10
+ const item = store.get(operationId);
11
+ if (item) {
12
+ return item;
13
+ }
14
+ }
15
+ return undefined;
16
+ }
17
+ }
18
+ exports.AggregatedStore = AggregatedStore;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InMemoryStore = void 0;
4
+ class InMemoryStore {
5
+ constructor(options) {
6
+ var _a;
7
+ this.storeData = (_a = options === null || options === void 0 ? void 0 : options.initialData) !== null && _a !== void 0 ? _a : new Map();
8
+ }
9
+ get(operationId) {
10
+ return this.storeData.get(operationId) || undefined;
11
+ }
12
+ prime(operationId, document) {
13
+ this.storeData.set(operationId, document);
14
+ }
15
+ clear(operationId) {
16
+ this.storeData.delete(operationId);
17
+ }
18
+ }
19
+ exports.InMemoryStore = InMemoryStore;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JsonFileStore = void 0;
4
+ const fs_1 = require("fs");
5
+ class JsonFileStore {
6
+ constructor() {
7
+ this.storeData = null;
8
+ }
9
+ get(operationId) {
10
+ if (!this.storeData) {
11
+ return undefined;
12
+ }
13
+ return this.storeData.get(operationId) || undefined;
14
+ }
15
+ loadFromFileSync(path) {
16
+ const data = JSON.parse((0, fs_1.readFileSync)(path, 'utf-8'));
17
+ this.storeData = new Map(Object.entries(data));
18
+ }
19
+ async loadFromFile(path) {
20
+ const data = JSON.parse(await fs_1.promises.readFile(path, 'utf-8'));
21
+ this.storeData = new Map(Object.entries(data));
22
+ }
23
+ }
24
+ exports.JsonFileStore = JsonFileStore;
package/cjs/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/cjs/utils.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.operationIdFromSource = void 0;
4
+ function operationIdFromSource(source) {
5
+ return typeof source === 'string' && source.length && source.indexOf('{') === -1 ? source : undefined;
6
+ }
7
+ exports.operationIdFromSource = operationIdFromSource;
package/esm/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types.js"), exports);
18
+ __exportStar(require("./utils.js"), exports);
19
+ __exportStar(require("./stores/aggregated-store.js"), exports);
20
+ __exportStar(require("./stores/inmemory-store.js"), exports);
21
+ __exportStar(require("./stores/json-file-store.js"), exports);
22
+ __exportStar(require("./plugin.js"), exports);
package/esm/plugin.js ADDED
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.usePersistedOperations = exports.readOperationId = void 0;
4
+ const graphql_1 = require("graphql");
5
+ const utils_js_1 = require("./utils.js");
6
+ const DEFAULT_OPTIONS = {
7
+ onlyPersisted: false,
8
+ };
9
+ const contextProperty = Symbol('persistedOperationId');
10
+ function readOperationId(context) {
11
+ return context[contextProperty];
12
+ }
13
+ exports.readOperationId = readOperationId;
14
+ const usePersistedOperations = (rawOptions) => {
15
+ const options = {
16
+ ...DEFAULT_OPTIONS,
17
+ ...(rawOptions || {}),
18
+ };
19
+ return {
20
+ onParse({ context, params, extendContext, setParsedDocument }) {
21
+ const operationId = options.extractOperationId ? options.extractOperationId(context) : (0, utils_js_1.operationIdFromSource)(params.source);
22
+ if (!operationId) {
23
+ if (options.onlyPersisted) {
24
+ throw new graphql_1.GraphQLError('Must provide operation id');
25
+ }
26
+ return;
27
+ }
28
+ const store = typeof options.store === 'function' ? options.store(context) : options.store;
29
+ if (!store) {
30
+ throw new graphql_1.GraphQLError('Must provide store for persisted-operations!');
31
+ }
32
+ const rawResult = store.get(operationId);
33
+ if (rawResult) {
34
+ const document = typeof rawResult === 'string' ? (0, graphql_1.parse)(rawResult) : rawResult;
35
+ extendContext({ [contextProperty]: operationId });
36
+ setParsedDocument(document);
37
+ return;
38
+ }
39
+ if (options.onMissingMatch)
40
+ options.onMissingMatch(context, operationId);
41
+ if (options.onlyPersisted) {
42
+ // we want to throw an error only when "onlyPersisted" is true, otherwise we let execution continue normally
43
+ throw new graphql_1.GraphQLError(`Unable to match operation with id '${operationId}'`);
44
+ }
45
+ // if we reach this stage we could not retrieve a persisted operation and we didn't throw any error as onlyPersisted is false
46
+ // hence we let operation continue assuming consumer is not passing an operation id, but a plain query string, with current request.
47
+ },
48
+ };
49
+ };
50
+ exports.usePersistedOperations = usePersistedOperations;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AggregatedStore = void 0;
4
+ class AggregatedStore {
5
+ constructor(stores) {
6
+ this.stores = stores;
7
+ }
8
+ get(operationId) {
9
+ for (const store of this.stores) {
10
+ const item = store.get(operationId);
11
+ if (item) {
12
+ return item;
13
+ }
14
+ }
15
+ return undefined;
16
+ }
17
+ }
18
+ exports.AggregatedStore = AggregatedStore;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InMemoryStore = void 0;
4
+ class InMemoryStore {
5
+ constructor(options) {
6
+ var _a;
7
+ this.storeData = (_a = options === null || options === void 0 ? void 0 : options.initialData) !== null && _a !== void 0 ? _a : new Map();
8
+ }
9
+ get(operationId) {
10
+ return this.storeData.get(operationId) || undefined;
11
+ }
12
+ prime(operationId, document) {
13
+ this.storeData.set(operationId, document);
14
+ }
15
+ clear(operationId) {
16
+ this.storeData.delete(operationId);
17
+ }
18
+ }
19
+ exports.InMemoryStore = InMemoryStore;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JsonFileStore = void 0;
4
+ const fs_1 = require("fs");
5
+ class JsonFileStore {
6
+ constructor() {
7
+ this.storeData = null;
8
+ }
9
+ get(operationId) {
10
+ if (!this.storeData) {
11
+ return undefined;
12
+ }
13
+ return this.storeData.get(operationId) || undefined;
14
+ }
15
+ loadFromFileSync(path) {
16
+ const data = JSON.parse((0, fs_1.readFileSync)(path, 'utf-8'));
17
+ this.storeData = new Map(Object.entries(data));
18
+ }
19
+ async loadFromFile(path) {
20
+ const data = JSON.parse(await fs_1.promises.readFile(path, 'utf-8'));
21
+ this.storeData = new Map(Object.entries(data));
22
+ }
23
+ }
24
+ exports.JsonFileStore = JsonFileStore;
package/esm/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/esm/utils.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.operationIdFromSource = void 0;
4
+ function operationIdFromSource(source) {
5
+ return typeof source === 'string' && source.length && source.indexOf('{') === -1 ? source : undefined;
6
+ }
7
+ exports.operationIdFromSource = operationIdFromSource;
package/package.json CHANGED
@@ -1,33 +1,54 @@
1
1
  {
2
2
  "name": "@envelop/persisted-operations",
3
- "version": "4.4.0-alpha-c0cc559.0",
3
+ "version": "4.4.0-alpha-e9434aa.0",
4
4
  "sideEffects": false,
5
5
  "peerDependencies": {
6
- "@envelop/core": "2.4.0-alpha-c0cc559.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
  "repository": {
10
10
  "type": "git",
11
- "url": "https://github.com/dotansimha/envelop.git",
11
+ "url": "https://github.com/n1ru4l/envelop.git",
12
12
  "directory": "packages/plugins/persisted-operations"
13
13
  },
14
14
  "author": "Dotan Simha <dotansimha@gmail.com>",
15
15
  "license": "MIT",
16
- "main": "index.js",
17
- "module": "index.mjs",
18
- "typings": "index.d.ts",
16
+ "main": "cjs/index.js",
17
+ "module": "esm/index.js",
18
+ "typings": "typings/index.d.ts",
19
19
  "typescript": {
20
- "definition": "index.d.ts"
20
+ "definition": "typings/index.d.ts"
21
21
  },
22
+ "type": "module",
22
23
  "exports": {
23
24
  ".": {
24
- "require": "./index.js",
25
- "import": "./index.mjs"
25
+ "require": {
26
+ "types": "./typings/index.d.ts",
27
+ "default": "./cjs/index.js"
28
+ },
29
+ "import": {
30
+ "types": "./typings/index.d.ts",
31
+ "default": "./esm/index.js"
32
+ },
33
+ "default": {
34
+ "types": "./typings/index.d.ts",
35
+ "default": "./esm/index.js"
36
+ }
26
37
  },
27
38
  "./*": {
28
- "require": "./*.js",
29
- "import": "./*.mjs"
39
+ "require": {
40
+ "types": "./typings/*.d.ts",
41
+ "default": "./cjs/*.js"
42
+ },
43
+ "import": {
44
+ "types": "./typings/*.d.ts",
45
+ "default": "./esm/*.js"
46
+ },
47
+ "default": {
48
+ "types": "./typings/*.d.ts",
49
+ "default": "./esm/*.js"
50
+ }
30
51
  },
31
52
  "./package.json": "./package.json"
32
53
  }
33
- }
54
+ }
@@ -0,0 +1,6 @@
1
+ export * from './types.js';
2
+ export * from './utils.js';
3
+ export * from './stores/aggregated-store.js';
4
+ export * from './stores/inmemory-store.js';
5
+ export * from './stores/json-file-store.js';
6
+ export * from './plugin.js';
@@ -1,5 +1,5 @@
1
1
  import { Plugin, DefaultContext } from '@envelop/core';
2
- import { PersistedOperationsFunctionStore, PersistedOperationsStore } from './types';
2
+ import { PersistedOperationsFunctionStore, PersistedOperationsStore } from './types.js';
3
3
  export declare type UsePersistedOperationsOptions<ContextType = DefaultContext> = {
4
4
  /**
5
5
  * Set to `false` to allow running operations that are not available in the store.
@@ -1,5 +1,5 @@
1
1
  import { DocumentNode } from 'graphql';
2
- import { PersistedOperationsStore } from '../types';
2
+ import { PersistedOperationsStore } from '../types.js';
3
3
  export declare class AggregatedStore implements PersistedOperationsStore {
4
4
  private stores;
5
5
  constructor(stores: PersistedOperationsStore[]);
@@ -1,5 +1,5 @@
1
1
  import { DocumentNode } from 'graphql';
2
- import { PersistedOperationsStore } from '../types';
2
+ import { PersistedOperationsStore } from '../types.js';
3
3
  export declare type InMemoryStoreDataMap = Map<string, DocumentNode | string>;
4
4
  export declare class InMemoryStore implements PersistedOperationsStore {
5
5
  private storeData;
@@ -1,5 +1,5 @@
1
1
  import { DocumentNode } from 'graphql';
2
- import { PersistedOperationsStore } from '../types';
2
+ import { PersistedOperationsStore } from '../types.js';
3
3
  export declare type JsonFileStoreDataMap = Map<string, DocumentNode | string>;
4
4
  export declare class JsonFileStore implements PersistedOperationsStore {
5
5
  private storeData;
File without changes
File without changes
package/README.md DELETED
@@ -1,127 +0,0 @@
1
- ## `@envelop/persisted-operations`
2
-
3
- This plugin allow you to enforce execution of persisted (hashed) operation, using a custom store.
4
-
5
- The idea behind running persisted operations is to allow clients to run only specific queries, that defined ahead of time. This provides an enhances security and disables (optionally) the execution of other operations. This plugin is useful if you are looking for a way to improve security and reduce network traffic.
6
-
7
- ## Getting Started
8
-
9
- ```
10
- yarn add @envelop/persisted-operations
11
- ```
12
-
13
- ## Usage Example
14
-
15
- The most basic implementation can use an in-memory JS `Map` wrapper with a `Store` object:
16
-
17
- ```ts
18
- import { envelop } from '@envelop/core';
19
- import { usePersistedOperations, InMemoryStore } from '@envelop/persisted-operations';
20
-
21
- // You can retrieve the store in any way (e.g. from a remote source) and implement it with a simple Map / Key->Value
22
- const myData = new Map();
23
- myData.set('persisted_1', parse(`query { ... }`));
24
- myData.set('persisted_2', 'query { ... }'));
25
-
26
- const store = new InMemoryStore({
27
- initialData: myData,
28
- })
29
-
30
- const getEnveloped = envelop({
31
- plugins: [
32
- // ... other plugins ...
33
- usePersistedOperations({
34
- store: myStore,
35
- }),
36
- ],
37
- });
38
- ```
39
-
40
- Now, when running operations through your GraphQL server, you can use a key instead of a query language:
41
-
42
- ```json
43
- {
44
- "query": "persisted_1",
45
- "variables": {}
46
- }
47
- ```
48
-
49
- You can also provide a function to retrieve the operation id from a custom property available in your context / incoming request:
50
-
51
- ```ts
52
- usePersistedOperations({
53
- store: myStore,
54
- extractOperationId: (context) => context.request.body.operationId // get id from custom property in body object
55
- }),
56
- ```
57
-
58
- ## Usage Example with built-in JsonFileStore
59
-
60
- ```ts
61
- import { usePersistedOperations, JsonFileStore } from '@envelop/persisted-operations';
62
-
63
- const persistedOperationsStore = new JsonFilesStore();
64
- const filePath = resolve(process.cwd(), 'assets/client1PersistedOperations.json');
65
-
66
- // sync
67
- persistedOperationsStore.loadFromFileSync(filePath); // load and parse persisted-operations files
68
-
69
- // or async
70
- await persistedOperationsStore.loadFromFile(filePath); // load and parse persisted-operations files
71
-
72
- const getEnveloped = envelop({
73
- plugins: [
74
- // ... other plugins ...
75
- usePersistedOperations({
76
- store: persistedOperationsStore,
77
- }),
78
- ],
79
- });
80
- ```
81
-
82
- ## Multiple Stores
83
-
84
- The `store` parameter accepts both a `Store` instance, or a function. If you need to support multiple stores (based on incoming GraphQL operation/HTTP request), you can provide a function to toggle between the stores, based on your needs:
85
-
86
- ```ts
87
- const getEnveloped = envelop({
88
- plugins: [
89
- // ... other plugins ...
90
- usePersistedOperations({
91
- store: context => {
92
- if (context.req.headers['user-agent'].includes('Android')) {
93
- return mobileClientsStore;
94
- }
95
-
96
- return defaultStore;
97
- },
98
- }),
99
- ],
100
- });
101
-
102
- // later, pass the initial context
103
- const proxyFns = getEnveloped({ req });
104
- ```
105
-
106
- ## Additional options
107
-
108
- ### onlyPersisted
109
-
110
- You can pass `onlyPersisted: true` when you want to allow persisted operations only in your server. In this case the plugin will issue a GraphQL error when it does not receive an operation Id, or when the received operation id is not available in your store/s.
111
-
112
- ### onMissingMatch
113
-
114
- You might want to perform some actions, such as logging custom events, when your operation Id is not matched in your store/s; in this case you can use the `onMissingMatch` callback function.
115
- The function receives the context and operationId as arguments, so you can use it like so:
116
-
117
- ```js
118
- onMissingMatch: (context, operationId) => {
119
- myEventPool.add(`Missing match for operation "${operationId}" from agent "${context.req.headers['user-agent']}"`);
120
- };
121
- ```
122
-
123
- ## With Relay
124
-
125
- If you are using Relay, you can leverage `relay-compiler` feature for hashing and and creating the store for you, during build.
126
-
127
- You can [read more about this feature here](https://relay.dev/docs/guides/persisted-queries/). After building your hashes, you can use `queryMap.json` as your store.
package/index.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export * from './types';
2
- export * from './utils';
3
- export * from './stores/aggregated-store';
4
- export * from './stores/inmemory-store';
5
- export * from './stores/json-file-store';
6
- export * from './plugin';
package/index.js DELETED
@@ -1,112 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const fs = require('fs');
6
- const graphql = require('graphql');
7
-
8
- function operationIdFromSource(source) {
9
- return typeof source === 'string' && source.length && source.indexOf('{') === -1 ? source : undefined;
10
- }
11
-
12
- class AggregatedStore {
13
- constructor(stores) {
14
- this.stores = stores;
15
- }
16
- get(operationId) {
17
- for (const store of this.stores) {
18
- const item = store.get(operationId);
19
- if (item) {
20
- return item;
21
- }
22
- }
23
- return undefined;
24
- }
25
- }
26
-
27
- class InMemoryStore {
28
- constructor(options) {
29
- var _a;
30
- this.storeData = (_a = options === null || options === void 0 ? void 0 : options.initialData) !== null && _a !== void 0 ? _a : new Map();
31
- }
32
- get(operationId) {
33
- return this.storeData.get(operationId) || undefined;
34
- }
35
- prime(operationId, document) {
36
- this.storeData.set(operationId, document);
37
- }
38
- clear(operationId) {
39
- this.storeData.delete(operationId);
40
- }
41
- }
42
-
43
- class JsonFileStore {
44
- constructor() {
45
- this.storeData = null;
46
- }
47
- get(operationId) {
48
- if (!this.storeData) {
49
- return undefined;
50
- }
51
- return this.storeData.get(operationId) || undefined;
52
- }
53
- loadFromFileSync(path) {
54
- const data = JSON.parse(fs.readFileSync(path, 'utf-8'));
55
- this.storeData = new Map(Object.entries(data));
56
- }
57
- async loadFromFile(path) {
58
- const data = JSON.parse(await fs.promises.readFile(path, 'utf-8'));
59
- this.storeData = new Map(Object.entries(data));
60
- }
61
- }
62
-
63
- const DEFAULT_OPTIONS = {
64
- onlyPersisted: false,
65
- };
66
- const contextProperty = Symbol('persistedOperationId');
67
- function readOperationId(context) {
68
- return context[contextProperty];
69
- }
70
- const usePersistedOperations = (rawOptions) => {
71
- const options = {
72
- ...DEFAULT_OPTIONS,
73
- ...(rawOptions || {}),
74
- };
75
- return {
76
- onParse({ context, params, extendContext, setParsedDocument }) {
77
- const operationId = options.extractOperationId ? options.extractOperationId(context) : operationIdFromSource(params.source);
78
- if (!operationId) {
79
- if (options.onlyPersisted) {
80
- throw new graphql.GraphQLError('Must provide operation id');
81
- }
82
- return;
83
- }
84
- const store = typeof options.store === 'function' ? options.store(context) : options.store;
85
- if (!store) {
86
- throw new graphql.GraphQLError('Must provide store for persisted-operations!');
87
- }
88
- const rawResult = store.get(operationId);
89
- if (rawResult) {
90
- const document = typeof rawResult === 'string' ? graphql.parse(rawResult) : rawResult;
91
- extendContext({ [contextProperty]: operationId });
92
- setParsedDocument(document);
93
- return;
94
- }
95
- if (options.onMissingMatch)
96
- options.onMissingMatch(context, operationId);
97
- if (options.onlyPersisted) {
98
- // we want to throw an error only when "onlyPersisted" is true, otherwise we let execution continue normally
99
- throw new graphql.GraphQLError(`Unable to match operation with id '${operationId}'`);
100
- }
101
- // if we reach this stage we could not retrieve a persisted operation and we didn't throw any error as onlyPersisted is false
102
- // hence we let operation continue assuming consumer is not passing an operation id, but a plain query string, with current request.
103
- },
104
- };
105
- };
106
-
107
- exports.AggregatedStore = AggregatedStore;
108
- exports.InMemoryStore = InMemoryStore;
109
- exports.JsonFileStore = JsonFileStore;
110
- exports.operationIdFromSource = operationIdFromSource;
111
- exports.readOperationId = readOperationId;
112
- exports.usePersistedOperations = usePersistedOperations;
package/index.mjs DELETED
@@ -1,103 +0,0 @@
1
- import { readFileSync, promises } from 'fs';
2
- import { GraphQLError, parse } from 'graphql';
3
-
4
- function operationIdFromSource(source) {
5
- return typeof source === 'string' && source.length && source.indexOf('{') === -1 ? source : undefined;
6
- }
7
-
8
- class AggregatedStore {
9
- constructor(stores) {
10
- this.stores = stores;
11
- }
12
- get(operationId) {
13
- for (const store of this.stores) {
14
- const item = store.get(operationId);
15
- if (item) {
16
- return item;
17
- }
18
- }
19
- return undefined;
20
- }
21
- }
22
-
23
- class InMemoryStore {
24
- constructor(options) {
25
- var _a;
26
- this.storeData = (_a = options === null || options === void 0 ? void 0 : options.initialData) !== null && _a !== void 0 ? _a : new Map();
27
- }
28
- get(operationId) {
29
- return this.storeData.get(operationId) || undefined;
30
- }
31
- prime(operationId, document) {
32
- this.storeData.set(operationId, document);
33
- }
34
- clear(operationId) {
35
- this.storeData.delete(operationId);
36
- }
37
- }
38
-
39
- class JsonFileStore {
40
- constructor() {
41
- this.storeData = null;
42
- }
43
- get(operationId) {
44
- if (!this.storeData) {
45
- return undefined;
46
- }
47
- return this.storeData.get(operationId) || undefined;
48
- }
49
- loadFromFileSync(path) {
50
- const data = JSON.parse(readFileSync(path, 'utf-8'));
51
- this.storeData = new Map(Object.entries(data));
52
- }
53
- async loadFromFile(path) {
54
- const data = JSON.parse(await promises.readFile(path, 'utf-8'));
55
- this.storeData = new Map(Object.entries(data));
56
- }
57
- }
58
-
59
- const DEFAULT_OPTIONS = {
60
- onlyPersisted: false,
61
- };
62
- const contextProperty = Symbol('persistedOperationId');
63
- function readOperationId(context) {
64
- return context[contextProperty];
65
- }
66
- const usePersistedOperations = (rawOptions) => {
67
- const options = {
68
- ...DEFAULT_OPTIONS,
69
- ...(rawOptions || {}),
70
- };
71
- return {
72
- onParse({ context, params, extendContext, setParsedDocument }) {
73
- const operationId = options.extractOperationId ? options.extractOperationId(context) : operationIdFromSource(params.source);
74
- if (!operationId) {
75
- if (options.onlyPersisted) {
76
- throw new GraphQLError('Must provide operation id');
77
- }
78
- return;
79
- }
80
- const store = typeof options.store === 'function' ? options.store(context) : options.store;
81
- if (!store) {
82
- throw new GraphQLError('Must provide store for persisted-operations!');
83
- }
84
- const rawResult = store.get(operationId);
85
- if (rawResult) {
86
- const document = typeof rawResult === 'string' ? parse(rawResult) : rawResult;
87
- extendContext({ [contextProperty]: operationId });
88
- setParsedDocument(document);
89
- return;
90
- }
91
- if (options.onMissingMatch)
92
- options.onMissingMatch(context, operationId);
93
- if (options.onlyPersisted) {
94
- // we want to throw an error only when "onlyPersisted" is true, otherwise we let execution continue normally
95
- throw new GraphQLError(`Unable to match operation with id '${operationId}'`);
96
- }
97
- // if we reach this stage we could not retrieve a persisted operation and we didn't throw any error as onlyPersisted is false
98
- // hence we let operation continue assuming consumer is not passing an operation id, but a plain query string, with current request.
99
- },
100
- };
101
- };
102
-
103
- export { AggregatedStore, InMemoryStore, JsonFileStore, operationIdFromSource, readOperationId, usePersistedOperations };