@graphql-mesh/plugin-rate-limit
Version:
92 lines (87 loc) • 4.37 kB
JavaScript
;
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
const stringInterpolation = require('@graphql-mesh/string-interpolation');
const crossHelpers = require('@graphql-mesh/cross-helpers');
const utils = require('@graphql-tools/utils');
const minimatch = _interopDefault(require('minimatch'));
const graphql = require('graphql');
function deleteNode(parent, remaining, currentKey) {
const nextKey = remaining.shift();
if (nextKey) {
const nextParent = currentKey ? parent[currentKey] : parent;
return deleteNode(nextParent, remaining, nextKey);
}
delete parent[currentKey];
}
function useMeshRateLimit(options) {
return {
async onExecute(onExecuteArgs) {
const typeInfo = new graphql.TypeInfo(onExecuteArgs.args.schema);
const errors = [];
const jobs = [];
let remainingFields = 0;
graphql.visit(onExecuteArgs.args.document, graphql.visitInParallel(options.config.map(config => {
const typeMatcher = new minimatch.Minimatch(config.type);
const fieldMatcher = new minimatch.Minimatch(config.field);
const identifier = stringInterpolation.stringInterpolator.parse(config.identifier, {
env: crossHelpers.process.env,
root: onExecuteArgs.args.rootValue,
context: onExecuteArgs.args.contextValue,
});
return graphql.visitWithTypeInfo(typeInfo, {
Field: (fieldNode, key, parent, path) => {
const parentType = typeInfo.getParentType();
if (typeMatcher.match(parentType.name)) {
const fieldDef = typeInfo.getFieldDef();
if (fieldMatcher.match(fieldDef.name)) {
const cacheKey = `rate-limit-${identifier}-${parentType.name}.${fieldDef.name}`;
const remainingTokens$ = options.cache.get(cacheKey);
jobs.push(remainingTokens$.then((remainingTokens) => {
var _a;
if (remainingTokens == null) {
remainingTokens = config.max;
}
if (remainingTokens === 0) {
errors.push(utils.createGraphQLError(`Rate limit of "${parentType.name}.${fieldDef.name}" exceeded for "${identifier}"`, {
path: [((_a = fieldNode.alias) === null || _a === void 0 ? void 0 : _a.value) || fieldDef.name],
}));
deleteNode(parent, [...path]);
remainingFields--;
return null;
}
return options.cache.set(cacheKey, remainingTokens - 1, {
ttl: config.ttl / 1000,
});
}));
}
}
remainingFields++;
return false;
},
});
})));
await Promise.all(jobs);
if (errors.length > 0) {
// If there is a field left in the final selection set
if (remainingFields > 0) {
// Add the errors to the final result
return {
onExecuteDone(onExecuteDoneArgs) {
onExecuteDoneArgs.setResult({
...onExecuteDoneArgs.result,
errors,
});
},
};
}
// If there is no need to continue the execution, stop
onExecuteArgs.setResultAndStopExecution({
data: null,
errors,
});
}
return undefined;
},
};
}
module.exports = useMeshRateLimit;