@graphql-mesh/plugin-rate-limit 0.0.1-alpha-ce3779bf5.0 → 0.0.1-alpha-e6c528698.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.
Files changed (3) hide show
  1. package/index.js +74 -51
  2. package/index.mjs +74 -51
  3. package/package.json +3 -3
package/index.js CHANGED
@@ -6,61 +6,84 @@ const stringInterpolation = require('@graphql-mesh/string-interpolation');
6
6
  const crossHelpers = require('@graphql-mesh/cross-helpers');
7
7
  const utils = require('@graphql-tools/utils');
8
8
  const minimatch = _interopDefault(require('minimatch'));
9
+ const graphql = require('graphql');
9
10
 
10
- function useMeshRateLimit(options) {
11
- const tokenMap = new Map();
12
- const timeouts = new Set();
13
- if (options.pubsub) {
14
- const id = options.pubsub.subscribe('destroy', () => {
15
- options.pubsub.unsubscribe(id);
16
- timeouts.forEach(timeout => clearTimeout(timeout));
17
- });
11
+ function deleteNode(parent, remaining, currentKey) {
12
+ const nextKey = remaining.shift();
13
+ if (nextKey) {
14
+ const nextParent = currentKey ? parent[currentKey] : parent;
15
+ return deleteNode(nextParent, remaining, nextKey);
18
16
  }
19
- const validationRuleFactories = options.config.map(config => {
20
- const typeMatcher = new minimatch.Minimatch(config.type);
21
- const fieldMatcher = new minimatch.Minimatch(config.field);
22
- return (context) => (validationContext) => ({
23
- Field: () => {
24
- const parentType = validationContext.getParentType();
25
- if (typeMatcher.match(parentType.name)) {
26
- const fieldDef = validationContext.getFieldDef();
27
- if (fieldMatcher.match(fieldDef.name)) {
28
- const identifier = stringInterpolation.stringInterpolator.parse(config.identifier, {
29
- env: crossHelpers.process.env,
30
- context,
31
- });
32
- const mapKey = `${identifier}-${parentType.name}.${fieldDef.name}`;
33
- let remainingTokens = tokenMap.get(mapKey);
34
- if (remainingTokens == null) {
35
- remainingTokens = config.max;
36
- const timeout = setTimeout(() => {
37
- tokenMap.delete(mapKey);
38
- timeouts.delete(timeout);
39
- }, config.ttl);
40
- timeouts.add(timeout);
41
- }
42
- if (remainingTokens === 0) {
43
- validationContext.reportError(utils.createGraphQLError(`Rate limit of "${parentType.name}.${fieldDef.name}" exceeded for "${identifier}"`, {
44
- path: [fieldDef.name],
45
- }));
46
- // Remove this field from the selection set
47
- return null;
48
- }
49
- else {
50
- tokenMap.set(mapKey, remainingTokens - 1);
17
+ delete parent[currentKey];
18
+ }
19
+ function useMeshRateLimit(options) {
20
+ return {
21
+ async onExecute(onExecuteArgs) {
22
+ const typeInfo = new graphql.TypeInfo(onExecuteArgs.args.schema);
23
+ const errors = [];
24
+ const jobs = [];
25
+ let remainingFields = 0;
26
+ graphql.visit(onExecuteArgs.args.document, graphql.visitInParallel(options.config.map(config => {
27
+ const typeMatcher = new minimatch.Minimatch(config.type);
28
+ const fieldMatcher = new minimatch.Minimatch(config.field);
29
+ const identifier = stringInterpolation.stringInterpolator.parse(config.identifier, {
30
+ env: crossHelpers.process.env,
31
+ root: onExecuteArgs.args.rootValue,
32
+ context: onExecuteArgs.args.contextValue,
33
+ });
34
+ return graphql.visitWithTypeInfo(typeInfo, {
35
+ Field: (fieldNode, key, parent, path) => {
36
+ const parentType = typeInfo.getParentType();
37
+ if (typeMatcher.match(parentType.name)) {
38
+ const fieldDef = typeInfo.getFieldDef();
39
+ if (fieldMatcher.match(fieldDef.name)) {
40
+ const cacheKey = `rate-limit-${identifier}-${parentType.name}.${fieldDef.name}`;
41
+ const remainingTokens$ = options.cache.get(cacheKey);
42
+ jobs.push(remainingTokens$.then((remainingTokens) => {
43
+ var _a;
44
+ if (remainingTokens == null) {
45
+ remainingTokens = config.max;
46
+ }
47
+ if (remainingTokens === 0) {
48
+ errors.push(utils.createGraphQLError(`Rate limit of "${parentType.name}.${fieldDef.name}" exceeded for "${identifier}"`, {
49
+ path: [((_a = fieldNode.alias) === null || _a === void 0 ? void 0 : _a.value) || fieldDef.name],
50
+ }));
51
+ deleteNode(parent, [...path]);
52
+ remainingFields--;
53
+ return null;
54
+ }
55
+ return options.cache.set(cacheKey, remainingTokens - 1, {
56
+ ttl: config.ttl / 1000,
57
+ });
58
+ }));
59
+ }
51
60
  }
52
- }
61
+ remainingFields++;
62
+ return false;
63
+ },
64
+ });
65
+ })));
66
+ await Promise.all(jobs);
67
+ if (errors.length > 0) {
68
+ // If there is a field left in the final selection set
69
+ if (remainingFields > 0) {
70
+ // Add the errors to the final result
71
+ return {
72
+ onExecuteDone(onExecuteDoneArgs) {
73
+ onExecuteDoneArgs.setResult({
74
+ ...onExecuteDoneArgs.result,
75
+ errors,
76
+ });
77
+ },
78
+ };
53
79
  }
54
- return false;
55
- },
56
- });
57
- });
58
- return {
59
- onValidate(onValidateParams) {
60
- validationRuleFactories.forEach(validationRuleFactory => {
61
- const validationRule = validationRuleFactory(onValidateParams.context);
62
- onValidateParams.addValidationRule(validationRule);
63
- });
80
+ // If there is no need to continue the execution, stop
81
+ onExecuteArgs.setResultAndStopExecution({
82
+ data: null,
83
+ errors,
84
+ });
85
+ }
86
+ return undefined;
64
87
  },
65
88
  };
66
89
  }
package/index.mjs CHANGED
@@ -2,61 +2,84 @@ import { stringInterpolator } from '@graphql-mesh/string-interpolation';
2
2
  import { process } from '@graphql-mesh/cross-helpers';
3
3
  import { createGraphQLError } from '@graphql-tools/utils';
4
4
  import minimatch from 'minimatch';
5
+ import { TypeInfo, visit, visitInParallel, visitWithTypeInfo } from 'graphql';
5
6
 
6
- function useMeshRateLimit(options) {
7
- const tokenMap = new Map();
8
- const timeouts = new Set();
9
- if (options.pubsub) {
10
- const id = options.pubsub.subscribe('destroy', () => {
11
- options.pubsub.unsubscribe(id);
12
- timeouts.forEach(timeout => clearTimeout(timeout));
13
- });
7
+ function deleteNode(parent, remaining, currentKey) {
8
+ const nextKey = remaining.shift();
9
+ if (nextKey) {
10
+ const nextParent = currentKey ? parent[currentKey] : parent;
11
+ return deleteNode(nextParent, remaining, nextKey);
14
12
  }
15
- const validationRuleFactories = options.config.map(config => {
16
- const typeMatcher = new minimatch.Minimatch(config.type);
17
- const fieldMatcher = new minimatch.Minimatch(config.field);
18
- return (context) => (validationContext) => ({
19
- Field: () => {
20
- const parentType = validationContext.getParentType();
21
- if (typeMatcher.match(parentType.name)) {
22
- const fieldDef = validationContext.getFieldDef();
23
- if (fieldMatcher.match(fieldDef.name)) {
24
- const identifier = stringInterpolator.parse(config.identifier, {
25
- env: process.env,
26
- context,
27
- });
28
- const mapKey = `${identifier}-${parentType.name}.${fieldDef.name}`;
29
- let remainingTokens = tokenMap.get(mapKey);
30
- if (remainingTokens == null) {
31
- remainingTokens = config.max;
32
- const timeout = setTimeout(() => {
33
- tokenMap.delete(mapKey);
34
- timeouts.delete(timeout);
35
- }, config.ttl);
36
- timeouts.add(timeout);
37
- }
38
- if (remainingTokens === 0) {
39
- validationContext.reportError(createGraphQLError(`Rate limit of "${parentType.name}.${fieldDef.name}" exceeded for "${identifier}"`, {
40
- path: [fieldDef.name],
41
- }));
42
- // Remove this field from the selection set
43
- return null;
44
- }
45
- else {
46
- tokenMap.set(mapKey, remainingTokens - 1);
13
+ delete parent[currentKey];
14
+ }
15
+ function useMeshRateLimit(options) {
16
+ return {
17
+ async onExecute(onExecuteArgs) {
18
+ const typeInfo = new TypeInfo(onExecuteArgs.args.schema);
19
+ const errors = [];
20
+ const jobs = [];
21
+ let remainingFields = 0;
22
+ visit(onExecuteArgs.args.document, visitInParallel(options.config.map(config => {
23
+ const typeMatcher = new minimatch.Minimatch(config.type);
24
+ const fieldMatcher = new minimatch.Minimatch(config.field);
25
+ const identifier = stringInterpolator.parse(config.identifier, {
26
+ env: process.env,
27
+ root: onExecuteArgs.args.rootValue,
28
+ context: onExecuteArgs.args.contextValue,
29
+ });
30
+ return visitWithTypeInfo(typeInfo, {
31
+ Field: (fieldNode, key, parent, path) => {
32
+ const parentType = typeInfo.getParentType();
33
+ if (typeMatcher.match(parentType.name)) {
34
+ const fieldDef = typeInfo.getFieldDef();
35
+ if (fieldMatcher.match(fieldDef.name)) {
36
+ const cacheKey = `rate-limit-${identifier}-${parentType.name}.${fieldDef.name}`;
37
+ const remainingTokens$ = options.cache.get(cacheKey);
38
+ jobs.push(remainingTokens$.then((remainingTokens) => {
39
+ var _a;
40
+ if (remainingTokens == null) {
41
+ remainingTokens = config.max;
42
+ }
43
+ if (remainingTokens === 0) {
44
+ errors.push(createGraphQLError(`Rate limit of "${parentType.name}.${fieldDef.name}" exceeded for "${identifier}"`, {
45
+ path: [((_a = fieldNode.alias) === null || _a === void 0 ? void 0 : _a.value) || fieldDef.name],
46
+ }));
47
+ deleteNode(parent, [...path]);
48
+ remainingFields--;
49
+ return null;
50
+ }
51
+ return options.cache.set(cacheKey, remainingTokens - 1, {
52
+ ttl: config.ttl / 1000,
53
+ });
54
+ }));
55
+ }
47
56
  }
48
- }
57
+ remainingFields++;
58
+ return false;
59
+ },
60
+ });
61
+ })));
62
+ await Promise.all(jobs);
63
+ if (errors.length > 0) {
64
+ // If there is a field left in the final selection set
65
+ if (remainingFields > 0) {
66
+ // Add the errors to the final result
67
+ return {
68
+ onExecuteDone(onExecuteDoneArgs) {
69
+ onExecuteDoneArgs.setResult({
70
+ ...onExecuteDoneArgs.result,
71
+ errors,
72
+ });
73
+ },
74
+ };
49
75
  }
50
- return false;
51
- },
52
- });
53
- });
54
- return {
55
- onValidate(onValidateParams) {
56
- validationRuleFactories.forEach(validationRuleFactory => {
57
- const validationRule = validationRuleFactory(onValidateParams.context);
58
- onValidateParams.addValidationRule(validationRule);
59
- });
76
+ // If there is no need to continue the execution, stop
77
+ onExecuteArgs.setResultAndStopExecution({
78
+ data: null,
79
+ errors,
80
+ });
81
+ }
82
+ return undefined;
60
83
  },
61
84
  };
62
85
  }
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@graphql-mesh/plugin-rate-limit",
3
- "version": "0.0.1-alpha-ce3779bf5.0",
3
+ "version": "0.0.1-alpha-e6c528698.0",
4
4
  "sideEffects": false,
5
5
  "peerDependencies": {
6
6
  "graphql": "*"
7
7
  },
8
8
  "dependencies": {
9
9
  "@envelop/core": "^2.3.2",
10
- "@graphql-mesh/cross-helpers": "0.1.6",
10
+ "@graphql-mesh/cross-helpers": "0.1.7-alpha-e6c528698.0",
11
11
  "@graphql-mesh/string-interpolation": "0.3.0",
12
- "@graphql-mesh/types": "0.77.0-alpha-ce3779bf5.0",
12
+ "@graphql-mesh/types": "0.77.0-alpha-e6c528698.0",
13
13
  "@graphql-tools/utils": "8.8.0",
14
14
  "minimatch": "5.1.0",
15
15
  "tslib": "^2.4.0"