@envelop/extended-validation 1.1.1-alpha-52fc7d2.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/README.md ADDED
@@ -0,0 +1,135 @@
1
+ ## `@envelop/extended-validation`
2
+
3
+ Extended validation plugin adds support for writing GraphQL validation rules, that has access to all `execute` parameters, including variables.
4
+
5
+ While GraphQL supports fair amount of built-in validations, and validations could be extended, it's doesn't expose `variables` to the validation rules, since operation variables are not available during `validate` flow (it's only available through execution of the operation, after input/variables coercion is done).
6
+
7
+ This plugin runs before `validate` but allow developers to write their validation rules in the same way GraphQL `ValidationRule` is defined (based on a GraphQL visitor).
8
+
9
+ ## Getting Started
10
+
11
+ Start by installing the plugin:
12
+
13
+ ```
14
+ yarn add @envelop/extended-validation
15
+ ```
16
+
17
+ Then, use the plugin with your validation rules:
18
+
19
+ ```ts
20
+ import { useExtendedValidation } from '@envelop/extended-validation';
21
+
22
+ const getEnveloped = evelop({
23
+ plugins: [
24
+ useExtendedValidation({
25
+ rules: [ ... ] // your rules here
26
+ })
27
+ ]
28
+ })
29
+ ```
30
+
31
+ To create your custom rules, implement the `ExtendedValidationRule` interface and return your GraphQL AST visitor.
32
+
33
+ For example:
34
+
35
+ ```ts
36
+ import { ExtendedValidationRule } from '@envelop/extended-validation';
37
+
38
+ export const MyRule: ExtendedValidationRule = (validationContext, executionArgs) => {
39
+ return {
40
+ OperationDefinition: node => {
41
+ // This will run for every executed Query/Mutation/Subscription
42
+ // And now you also have access to the execution params like variables, context and so on.
43
+ // If you wish to report an error, use validationContext.reportError or throw an exception.
44
+ },
45
+ };
46
+ };
47
+ ```
48
+
49
+ ## Built-in Rules
50
+
51
+ ### Union Inputs: `@oneOf`
52
+
53
+ This directive provides validation for input types and implements the concept of union inputs. You can find the [complete spec RFC here](https://github.com/graphql/graphql-spec/pull/825).
54
+
55
+ You can use union inputs either via a the SDL flow, by annotating types and fields with `@oneOf` or via the `extensions` field.
56
+
57
+ First, make sure to add that rule to your plugin usage:
58
+
59
+ ```ts
60
+ import { useExtendedValidation, OneOfInputObjectsRule } from '@envelop/extended-validation';
61
+
62
+ const getEnveloped = evelop({
63
+ plugins: [
64
+ useExtendedValidation({
65
+ rules: [OneOfInputObjectsRule],
66
+ }),
67
+ ],
68
+ });
69
+ ```
70
+
71
+ #### Schema Directive Flow
72
+
73
+ Make sure to include the following directive in your schema:
74
+
75
+ ```graphql
76
+ directive @oneOf on INPUT_OBJECT | FIELD_DEFINITION
77
+ ```
78
+
79
+ Then, apply it to field definitions, or to a complete `input` type:
80
+
81
+ ```graphql
82
+ ## Apply to entire input type
83
+ input FindUserInput @oneOf {
84
+ id: ID
85
+ organizationAndRegistrationNumber: GraphQLInt
86
+ }
87
+
88
+ ## Or, apply to a set of input arguments
89
+
90
+ type Query {
91
+ foo(id: ID, str1: String, str2: String): String @oneOf
92
+ }
93
+ ```
94
+
95
+ #### Programmatic extensions flow
96
+
97
+ ```tsx
98
+ const GraphQLFindUserInput = new GraphQLInputObjectType({
99
+ name: 'FindUserInput',
100
+ fields: {
101
+ id: {
102
+ type: GraphQLID,
103
+ },
104
+ organizationAndRegistrationNumber: {
105
+ type: GraphQLInt,
106
+ },
107
+ },
108
+ extensions: {
109
+ oneOf: true,
110
+ },
111
+ });
112
+
113
+ const Query = new GraphQLObjectType({
114
+ name: 'Query',
115
+ fields: {
116
+ foo: {
117
+ type: GraphQLString,
118
+ args: {
119
+ id: {
120
+ type: GraphQLID,
121
+ },
122
+ str1: {
123
+ type: GraphQLString,
124
+ },
125
+ str2: {
126
+ type: GraphQLString,
127
+ },
128
+ },
129
+ extensions: {
130
+ oneOf: true,
131
+ },
132
+ },
133
+ },
134
+ });
135
+ ```
package/common.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { ASTVisitor, DirectiveNode, ExecutionArgs, GraphQLNamedType, GraphQLType, ValidationContext } from 'graphql';
2
+ export declare type ExtendedValidationRule = (context: ValidationContext, executionArgs: ExecutionArgs) => ASTVisitor;
3
+ export declare function getDirectiveFromAstNode(astNode: {
4
+ directives?: ReadonlyArray<DirectiveNode>;
5
+ }, names: string | string[]): null | DirectiveNode;
6
+ export declare function unwrapType(type: GraphQLType): GraphQLNamedType;
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './plugin';
2
+ export * from './common';
3
+ export * from './rules/one-of';
package/index.js ADDED
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const graphql = require('graphql');
6
+ const values_js = require('graphql/execution/values.js');
7
+
8
+ const SYMBOL_EXTENDED_VALIDATION_RULES = Symbol('SYMBOL_EXTENDED_VALIDATION_RULES');
9
+ const useExtendedValidation = (options) => {
10
+ let schemaTypeInfo;
11
+ return {
12
+ onSchemaChange({ schema }) {
13
+ schemaTypeInfo = new graphql.TypeInfo(schema);
14
+ },
15
+ onParse({ context, extendContext }) {
16
+ var _a;
17
+ const rules = (_a = context === null || context === void 0 ? void 0 : context[SYMBOL_EXTENDED_VALIDATION_RULES]) !== null && _a !== void 0 ? _a : [];
18
+ rules.push(...options.rules);
19
+ extendContext({
20
+ [SYMBOL_EXTENDED_VALIDATION_RULES]: rules,
21
+ });
22
+ },
23
+ onExecute({ args, setResultAndStopExecution }) {
24
+ const rules = args.contextValue[SYMBOL_EXTENDED_VALIDATION_RULES];
25
+ const errors = [];
26
+ const typeInfo = schemaTypeInfo || new graphql.TypeInfo(args.schema);
27
+ const validationContext = new graphql.ValidationContext(args.schema, args.document, typeInfo, e => {
28
+ errors.push(e);
29
+ });
30
+ const visitor = graphql.visitInParallel(rules.map(rule => rule(validationContext, args)));
31
+ graphql.visit(args.document, graphql.visitWithTypeInfo(typeInfo, visitor));
32
+ for (const rule of rules) {
33
+ rule(validationContext, args);
34
+ }
35
+ if (errors.length > 0) {
36
+ let result = {
37
+ data: null,
38
+ errors,
39
+ };
40
+ if (options.onValidationFailed) {
41
+ options.onValidationFailed({ args, result, setResult: newResult => (result = newResult) });
42
+ }
43
+ return setResultAndStopExecution(result);
44
+ }
45
+ },
46
+ };
47
+ };
48
+
49
+ function getDirectiveFromAstNode(astNode, names) {
50
+ const directives = astNode.directives || [];
51
+ const namesArr = Array.isArray(names) ? names : [names];
52
+ const authDirective = directives.find(d => namesArr.includes(d.name.value));
53
+ return authDirective || null;
54
+ }
55
+ function unwrapType(type) {
56
+ if (graphql.isNonNullType(type) || graphql.isListType(type)) {
57
+ return unwrapType(type.ofType);
58
+ }
59
+ return type;
60
+ }
61
+
62
+ const ONE_OF_DIRECTIVE_SDL = /* GraphQL */ `
63
+ directive @oneOf on INPUT_OBJECT | FIELD_DEFINITION
64
+ `;
65
+ const OneOfInputObjectsRule = (validationContext, executionArgs) => {
66
+ return {
67
+ Field: node => {
68
+ var _a, _b;
69
+ if ((_a = node.arguments) === null || _a === void 0 ? void 0 : _a.length) {
70
+ const fieldType = validationContext.getFieldDef();
71
+ if (!fieldType) {
72
+ return;
73
+ }
74
+ const values = values_js.getArgumentValues(fieldType, node, executionArgs.variableValues);
75
+ if (fieldType) {
76
+ const isOneOfFieldType = ((_b = fieldType.extensions) === null || _b === void 0 ? void 0 : _b.oneOf) || (fieldType.astNode && getDirectiveFromAstNode(fieldType.astNode, 'oneOf'));
77
+ if (isOneOfFieldType) {
78
+ if (Object.keys(values).length !== 1) {
79
+ validationContext.reportError(new graphql.GraphQLError(`Exactly one key must be specified for input for field "${fieldType.type.toString()}.${node.name.value}"`, [node]));
80
+ }
81
+ }
82
+ }
83
+ for (const arg of node.arguments) {
84
+ const argType = fieldType.args.find(typeArg => typeArg.name === arg.name.value);
85
+ if (argType) {
86
+ traverseVariables(validationContext, arg, argType.type, values[arg.name.value]);
87
+ }
88
+ }
89
+ }
90
+ },
91
+ };
92
+ };
93
+ function traverseVariables(validationContext, arg, graphqlType, currentValue) {
94
+ var _a;
95
+ // if the current value is empty we don't need to traverse deeper
96
+ // if it shouldn't be empty, the "original" validation phase should complain.
97
+ if (currentValue == null) {
98
+ return;
99
+ }
100
+ if (graphql.isListType(graphqlType)) {
101
+ if (!Array.isArray(currentValue)) {
102
+ // because of graphql type coercion a single object should be treated as an array of one object
103
+ currentValue = [currentValue];
104
+ }
105
+ currentValue.forEach(value => {
106
+ traverseVariables(validationContext, arg, graphqlType.ofType, value);
107
+ });
108
+ return;
109
+ }
110
+ if (typeof currentValue !== 'object' || currentValue == null) {
111
+ // in case the value is not an object, the "original" validation phase should complain.
112
+ return;
113
+ }
114
+ const inputType = unwrapType(graphqlType);
115
+ const isOneOfInputType = ((_a = inputType.extensions) === null || _a === void 0 ? void 0 : _a.oneOf) || (inputType.astNode && getDirectiveFromAstNode(inputType.astNode, 'oneOf'));
116
+ if (isOneOfInputType) {
117
+ if (Object.keys(currentValue).length !== 1) {
118
+ validationContext.reportError(new graphql.GraphQLError(`Exactly one key must be specified for input type "${inputType.name}"`, [arg]));
119
+ }
120
+ }
121
+ if (inputType instanceof graphql.GraphQLInputObjectType) {
122
+ for (const [name, fieldConfig] of Object.entries(inputType.getFields())) {
123
+ traverseVariables(validationContext, arg, fieldConfig.type, currentValue[name]);
124
+ }
125
+ }
126
+ }
127
+
128
+ exports.ONE_OF_DIRECTIVE_SDL = ONE_OF_DIRECTIVE_SDL;
129
+ exports.OneOfInputObjectsRule = OneOfInputObjectsRule;
130
+ exports.getDirectiveFromAstNode = getDirectiveFromAstNode;
131
+ exports.unwrapType = unwrapType;
132
+ exports.useExtendedValidation = useExtendedValidation;
package/index.mjs ADDED
@@ -0,0 +1,124 @@
1
+ import { TypeInfo, ValidationContext, visitInParallel, visit, visitWithTypeInfo, isNonNullType, isListType, GraphQLError, GraphQLInputObjectType } from 'graphql';
2
+ import { getArgumentValues } from 'graphql/execution/values.js';
3
+
4
+ const SYMBOL_EXTENDED_VALIDATION_RULES = Symbol('SYMBOL_EXTENDED_VALIDATION_RULES');
5
+ const useExtendedValidation = (options) => {
6
+ let schemaTypeInfo;
7
+ return {
8
+ onSchemaChange({ schema }) {
9
+ schemaTypeInfo = new TypeInfo(schema);
10
+ },
11
+ onParse({ context, extendContext }) {
12
+ var _a;
13
+ const rules = (_a = context === null || context === void 0 ? void 0 : context[SYMBOL_EXTENDED_VALIDATION_RULES]) !== null && _a !== void 0 ? _a : [];
14
+ rules.push(...options.rules);
15
+ extendContext({
16
+ [SYMBOL_EXTENDED_VALIDATION_RULES]: rules,
17
+ });
18
+ },
19
+ onExecute({ args, setResultAndStopExecution }) {
20
+ const rules = args.contextValue[SYMBOL_EXTENDED_VALIDATION_RULES];
21
+ const errors = [];
22
+ const typeInfo = schemaTypeInfo || new TypeInfo(args.schema);
23
+ const validationContext = new ValidationContext(args.schema, args.document, typeInfo, e => {
24
+ errors.push(e);
25
+ });
26
+ const visitor = visitInParallel(rules.map(rule => rule(validationContext, args)));
27
+ visit(args.document, visitWithTypeInfo(typeInfo, visitor));
28
+ for (const rule of rules) {
29
+ rule(validationContext, args);
30
+ }
31
+ if (errors.length > 0) {
32
+ let result = {
33
+ data: null,
34
+ errors,
35
+ };
36
+ if (options.onValidationFailed) {
37
+ options.onValidationFailed({ args, result, setResult: newResult => (result = newResult) });
38
+ }
39
+ return setResultAndStopExecution(result);
40
+ }
41
+ },
42
+ };
43
+ };
44
+
45
+ function getDirectiveFromAstNode(astNode, names) {
46
+ const directives = astNode.directives || [];
47
+ const namesArr = Array.isArray(names) ? names : [names];
48
+ const authDirective = directives.find(d => namesArr.includes(d.name.value));
49
+ return authDirective || null;
50
+ }
51
+ function unwrapType(type) {
52
+ if (isNonNullType(type) || isListType(type)) {
53
+ return unwrapType(type.ofType);
54
+ }
55
+ return type;
56
+ }
57
+
58
+ const ONE_OF_DIRECTIVE_SDL = /* GraphQL */ `
59
+ directive @oneOf on INPUT_OBJECT | FIELD_DEFINITION
60
+ `;
61
+ const OneOfInputObjectsRule = (validationContext, executionArgs) => {
62
+ return {
63
+ Field: node => {
64
+ var _a, _b;
65
+ if ((_a = node.arguments) === null || _a === void 0 ? void 0 : _a.length) {
66
+ const fieldType = validationContext.getFieldDef();
67
+ if (!fieldType) {
68
+ return;
69
+ }
70
+ const values = getArgumentValues(fieldType, node, executionArgs.variableValues);
71
+ if (fieldType) {
72
+ const isOneOfFieldType = ((_b = fieldType.extensions) === null || _b === void 0 ? void 0 : _b.oneOf) || (fieldType.astNode && getDirectiveFromAstNode(fieldType.astNode, 'oneOf'));
73
+ if (isOneOfFieldType) {
74
+ if (Object.keys(values).length !== 1) {
75
+ validationContext.reportError(new GraphQLError(`Exactly one key must be specified for input for field "${fieldType.type.toString()}.${node.name.value}"`, [node]));
76
+ }
77
+ }
78
+ }
79
+ for (const arg of node.arguments) {
80
+ const argType = fieldType.args.find(typeArg => typeArg.name === arg.name.value);
81
+ if (argType) {
82
+ traverseVariables(validationContext, arg, argType.type, values[arg.name.value]);
83
+ }
84
+ }
85
+ }
86
+ },
87
+ };
88
+ };
89
+ function traverseVariables(validationContext, arg, graphqlType, currentValue) {
90
+ var _a;
91
+ // if the current value is empty we don't need to traverse deeper
92
+ // if it shouldn't be empty, the "original" validation phase should complain.
93
+ if (currentValue == null) {
94
+ return;
95
+ }
96
+ if (isListType(graphqlType)) {
97
+ if (!Array.isArray(currentValue)) {
98
+ // because of graphql type coercion a single object should be treated as an array of one object
99
+ currentValue = [currentValue];
100
+ }
101
+ currentValue.forEach(value => {
102
+ traverseVariables(validationContext, arg, graphqlType.ofType, value);
103
+ });
104
+ return;
105
+ }
106
+ if (typeof currentValue !== 'object' || currentValue == null) {
107
+ // in case the value is not an object, the "original" validation phase should complain.
108
+ return;
109
+ }
110
+ const inputType = unwrapType(graphqlType);
111
+ const isOneOfInputType = ((_a = inputType.extensions) === null || _a === void 0 ? void 0 : _a.oneOf) || (inputType.astNode && getDirectiveFromAstNode(inputType.astNode, 'oneOf'));
112
+ if (isOneOfInputType) {
113
+ if (Object.keys(currentValue).length !== 1) {
114
+ validationContext.reportError(new GraphQLError(`Exactly one key must be specified for input type "${inputType.name}"`, [arg]));
115
+ }
116
+ }
117
+ if (inputType instanceof GraphQLInputObjectType) {
118
+ for (const [name, fieldConfig] of Object.entries(inputType.getFields())) {
119
+ traverseVariables(validationContext, arg, fieldConfig.type, currentValue[name]);
120
+ }
121
+ }
122
+ }
123
+
124
+ export { ONE_OF_DIRECTIVE_SDL, OneOfInputObjectsRule, getDirectiveFromAstNode, unwrapType, useExtendedValidation };
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@envelop/extended-validation",
3
+ "version": "1.1.1-alpha-52fc7d2.0",
4
+ "sideEffects": false,
5
+ "peerDependencies": {
6
+ "graphql": "^14.0.0 || ^15.0.0"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/dotansimha/envelop.git",
11
+ "directory": "packages/plugins/extended-validation"
12
+ },
13
+ "author": "Dotan Simha <dotansimha@gmail.com>",
14
+ "license": "MIT",
15
+ "main": "index.js",
16
+ "module": "index.mjs",
17
+ "typings": "index.d.ts",
18
+ "typescript": {
19
+ "definition": "index.d.ts"
20
+ },
21
+ "exports": {
22
+ ".": {
23
+ "require": "./index.js",
24
+ "import": "./index.mjs"
25
+ },
26
+ "./*": {
27
+ "require": "./*.js",
28
+ "import": "./*.mjs"
29
+ }
30
+ }
31
+ }
package/plugin.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { Plugin } from '@envelop/types';
2
+ import { ExecutionArgs, ExecutionResult } from 'graphql';
3
+ import { ExtendedValidationRule } from './common';
4
+ export declare const useExtendedValidation: (options: {
5
+ rules: ExtendedValidationRule[];
6
+ /**
7
+ * Callback that is invoked if the extended validation yields any errors.
8
+ */
9
+ onValidationFailed?: ((params: {
10
+ args: ExecutionArgs;
11
+ result: ExecutionResult;
12
+ setResult: (result: ExecutionResult) => void;
13
+ }) => void) | undefined;
14
+ }) => Plugin;
@@ -0,0 +1,3 @@
1
+ import { ExtendedValidationRule } from '../common';
2
+ export declare const ONE_OF_DIRECTIVE_SDL = "\n directive @oneOf on INPUT_OBJECT | FIELD_DEFINITION\n";
3
+ export declare const OneOfInputObjectsRule: ExtendedValidationRule;