@graphql-mesh/plugin-rate-limit 0.0.1-alpha-913ba159c.0 → 0.0.1-alpha-2ab01da12.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 +77 -49
  2. package/index.mjs +75 -49
  3. package/package.json +3 -2
package/index.js CHANGED
@@ -1,61 +1,89 @@
1
1
  'use strict';
2
2
 
3
+ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
4
+
3
5
  const stringInterpolation = require('@graphql-mesh/string-interpolation');
4
6
  const crossHelpers = require('@graphql-mesh/cross-helpers');
5
7
  const utils = require('@graphql-tools/utils');
8
+ const minimatch = _interopDefault(require('minimatch'));
9
+ const graphql = require('graphql');
6
10
 
7
- function useMeshRateLimit(options) {
8
- const pathRateLimitDef = new Map();
9
- const tokenMap = new Map();
10
- const timeouts = new Set();
11
- if (options.config) {
12
- options.config.forEach(config => {
13
- pathRateLimitDef.set(`${config.type}.${config.field}`, config);
14
- });
15
- }
16
- if (options.pubsub) {
17
- const id = options.pubsub.subscribe('destroy', () => {
18
- options.pubsub.unsubscribe(id);
19
- timeouts.forEach(timeout => clearTimeout(timeout));
20
- });
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);
21
16
  }
17
+ delete parent[currentKey];
18
+ }
19
+ function useMeshRateLimit(options) {
22
20
  return {
23
- onValidate(onValidateParams) {
24
- onValidateParams.addValidationRule(validationContext => ({
25
- Field: () => {
26
- const parentType = validationContext.getParentType();
27
- const fieldDef = validationContext.getFieldDef();
28
- const path = `${parentType.name}.${fieldDef.name}`;
29
- const rateLimitConfig = pathRateLimitDef.get(path);
30
- if (rateLimitConfig) {
31
- const identifier = stringInterpolation.stringInterpolator.parse(rateLimitConfig.identifier, {
32
- env: crossHelpers.process.env,
33
- context: onValidateParams.context,
34
- });
35
- const mapKey = `${identifier}-${path}`;
36
- let remainingTokens = tokenMap.get(mapKey);
37
- if (remainingTokens == null) {
38
- remainingTokens = rateLimitConfig.max;
39
- const timeout = setTimeout(() => {
40
- tokenMap.delete(mapKey);
41
- timeouts.delete(timeout);
42
- }, rateLimitConfig.ttl);
43
- timeouts.add(timeout);
44
- }
45
- if (remainingTokens === 0) {
46
- validationContext.reportError(utils.createGraphQLError(`Rate limit of "${path}" exceeded for "${identifier}"`, {
47
- path: [fieldDef.name],
48
- }));
49
- // Remove this field from the selection set
50
- return null;
51
- }
52
- else {
53
- tokenMap.set(mapKey, remainingTokens - 1);
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
+ }
54
60
  }
55
- }
56
- return false;
57
- },
58
- }));
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
+ };
79
+ }
80
+ // If there is no need to continue the execution, stop
81
+ onExecuteArgs.setResultAndStopExecution({
82
+ data: null,
83
+ errors,
84
+ });
85
+ }
86
+ return undefined;
59
87
  },
60
88
  };
61
89
  }
package/index.mjs CHANGED
@@ -1,59 +1,85 @@
1
1
  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
+ import minimatch from 'minimatch';
5
+ import { TypeInfo, visit, visitInParallel, visitWithTypeInfo } from 'graphql';
4
6
 
5
- function useMeshRateLimit(options) {
6
- const pathRateLimitDef = new Map();
7
- const tokenMap = new Map();
8
- const timeouts = new Set();
9
- if (options.config) {
10
- options.config.forEach(config => {
11
- pathRateLimitDef.set(`${config.type}.${config.field}`, config);
12
- });
13
- }
14
- if (options.pubsub) {
15
- const id = options.pubsub.subscribe('destroy', () => {
16
- options.pubsub.unsubscribe(id);
17
- timeouts.forEach(timeout => clearTimeout(timeout));
18
- });
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);
19
12
  }
13
+ delete parent[currentKey];
14
+ }
15
+ function useMeshRateLimit(options) {
20
16
  return {
21
- onValidate(onValidateParams) {
22
- onValidateParams.addValidationRule(validationContext => ({
23
- Field: () => {
24
- const parentType = validationContext.getParentType();
25
- const fieldDef = validationContext.getFieldDef();
26
- const path = `${parentType.name}.${fieldDef.name}`;
27
- const rateLimitConfig = pathRateLimitDef.get(path);
28
- if (rateLimitConfig) {
29
- const identifier = stringInterpolator.parse(rateLimitConfig.identifier, {
30
- env: process.env,
31
- context: onValidateParams.context,
32
- });
33
- const mapKey = `${identifier}-${path}`;
34
- let remainingTokens = tokenMap.get(mapKey);
35
- if (remainingTokens == null) {
36
- remainingTokens = rateLimitConfig.max;
37
- const timeout = setTimeout(() => {
38
- tokenMap.delete(mapKey);
39
- timeouts.delete(timeout);
40
- }, rateLimitConfig.ttl);
41
- timeouts.add(timeout);
42
- }
43
- if (remainingTokens === 0) {
44
- validationContext.reportError(createGraphQLError(`Rate limit of "${path}" exceeded for "${identifier}"`, {
45
- path: [fieldDef.name],
46
- }));
47
- // Remove this field from the selection set
48
- return null;
49
- }
50
- else {
51
- tokenMap.set(mapKey, remainingTokens - 1);
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
+ }
52
56
  }
53
- }
54
- return false;
55
- },
56
- }));
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
+ };
75
+ }
76
+ // If there is no need to continue the execution, stop
77
+ onExecuteArgs.setResultAndStopExecution({
78
+ data: null,
79
+ errors,
80
+ });
81
+ }
82
+ return undefined;
57
83
  },
58
84
  };
59
85
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@graphql-mesh/plugin-rate-limit",
3
- "version": "0.0.1-alpha-913ba159c.0",
3
+ "version": "0.0.1-alpha-2ab01da12.0",
4
4
  "sideEffects": false,
5
5
  "peerDependencies": {
6
6
  "graphql": "*"
@@ -9,8 +9,9 @@
9
9
  "@envelop/core": "^2.3.2",
10
10
  "@graphql-mesh/cross-helpers": "0.1.6",
11
11
  "@graphql-mesh/string-interpolation": "0.3.0",
12
- "@graphql-mesh/types": "0.77.0-alpha-913ba159c.0",
12
+ "@graphql-mesh/types": "0.77.0-alpha-2ab01da12.0",
13
13
  "@graphql-tools/utils": "8.8.0",
14
+ "minimatch": "5.1.0",
14
15
  "tslib": "^2.4.0"
15
16
  },
16
17
  "repository": {