graphql-shield
Version:
GraphQL Server permissions as another layer of abstraction!
46 lines (45 loc) • 1.54 kB
JavaScript
import hash from 'object-hash';
import { middleware } from 'graphql-middleware';
import { ValidationError, validateRuleTree } from './validation.js';
import { generateMiddlewareGeneratorFromRuleTree } from './generator.js';
import { allow } from './constructors.js';
import { withDefault } from './utils.js';
/**
*
* @param options
*
* Makes sure all of defined rules are in accord with the options
* shield can process.
*
*/
function normalizeOptions(options) {
if (typeof options.fallbackError === 'string') {
options.fallbackError = new Error(options.fallbackError);
}
return {
debug: options.debug !== undefined ? options.debug : false,
allowExternalErrors: withDefault(false)(options.allowExternalErrors),
fallbackRule: withDefault(allow)(options.fallbackRule),
fallbackError: withDefault(new Error('Not Authorised!'))(options.fallbackError),
hashFunction: withDefault(hash)(options.hashFunction),
};
}
/**
*
* @param ruleTree
* @param options
*
* Validates rules and generates middleware from defined rule tree.
*
*/
export function shield(ruleTree, options = {}) {
const normalizedOptions = normalizeOptions(options);
const ruleTreeValidity = validateRuleTree(ruleTree);
if (ruleTreeValidity.status === 'ok') {
const generatorFunction = generateMiddlewareGeneratorFromRuleTree(ruleTree, normalizedOptions);
return middleware(generatorFunction);
}
else {
throw new ValidationError(ruleTreeValidity.message);
}
}