Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New plugin: useExtendedValidation and implementation of @oneOf directive #149

Merged
merged 4 commits into from
May 2, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/poor-eagles-drop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@envelop/extended-validation': patch
---

NEW PLUGIN!
6 changes: 6 additions & 0 deletions .changeset/purple-bugs-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@envelop/core': patch
'@envelop/types': patch
---

Allow plugins to stop execution and return errors
13 changes: 12 additions & 1 deletion packages/core/src/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,16 +297,23 @@ export function envelop(options: { plugins: Plugin[]; extends?: Envelop[]; initi

const onResolversHandlers: OnResolverCalledHooks[] = [];
let executeFn: typeof execute = execute;
let result: ExecutionResult;

const afterCalls: ((options: { result: ExecutionResult; setResult: (newResult: ExecutionResult) => void }) => void)[] = [];
let context = args.contextValue;

for (const plugin of beforeExecuteCalls) {
let stopCalled = false;

const after = plugin.onExecute({
executeFn,
setExecuteFn: newExecuteFn => {
executeFn = newExecuteFn;
},
setResultAndStopExecution: stopResult => {
stopCalled = true;
result = stopResult;
},
extendContext: extension => {
if (typeof extension === 'object') {
context = {
Expand All @@ -322,6 +329,10 @@ export function envelop(options: { plugins: Plugin[]; extends?: Envelop[]; initi
args,
});

if (stopCalled) {
return result;
}

if (after) {
if (after.onExecuteDone) {
afterCalls.push(after.onExecuteDone);
Expand All @@ -336,7 +347,7 @@ export function envelop(options: { plugins: Plugin[]; extends?: Envelop[]; initi
context[resolversHooksSymbol] = onResolversHandlers;
}

let result = await executeFn({
result = await executeFn({
...args,
contextValue: context,
});
Expand Down
38 changes: 38 additions & 0 deletions packages/plugins/extended-validation/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"name": "@envelop/extended-validation",
"version": "0.0.0",
"author": "Dotan Simha <dotansimha@gmail.com>",
"license": "MIT",
"sideEffects": false,
"repository": {
"type": "git",
"url": "https://github.com/dotansimha/envelop.git",
"directory": "packages/plugins/extended-validation"
},
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"typings": "dist/index.d.ts",
"typescript": {
"definition": "dist/index.d.ts"
},
"scripts": {
"test": "jest",
"prepack": "bob prepack"
},
"dependencies": {},
"devDependencies": {
"bob-the-bundler": "1.2.0",
"graphql": "15.5.0",
"typescript": "4.2.4"
},
"peerDependencies": {
"graphql": "^14.0.0 || ^15.0.0"
},
"buildOptions": {
"input": "./src/index.ts"
},
"publishConfig": {
"directory": "dist",
"access": "public"
}
}
11 changes: 11 additions & 0 deletions packages/plugins/extended-validation/src/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { ASTVisitor, DirectiveNode, ExecutionArgs, GraphQLNamedType, ValidationContext } from 'graphql';

export type ExtendedValidationRule = (context: ValidationContext, executionArgs: ExecutionArgs) => ASTVisitor;

export function getDirectiveFromType(type: GraphQLNamedType, name: string): null | DirectiveNode {
const astNode = type.astNode;
const directives = astNode.directives;
const authDirective = directives.find(d => d.name.value === name);

return authDirective || null;
}
4 changes: 4 additions & 0 deletions packages/plugins/extended-validation/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './plugin';
export * from './common';

export * from './rules/one-of';
34 changes: 34 additions & 0 deletions packages/plugins/extended-validation/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Plugin } from '@envelop/types';
import { GraphQLError, TypeInfo, ValidationContext, visit, visitInParallel, visitWithTypeInfo } from 'graphql';
import { ExtendedValidationRule } from './common';

export const useExtendedValidation = (options: { rules: ExtendedValidationRule[] }): Plugin => {
let schemaTypeInfo: TypeInfo;

return {
onSchemaChange({ schema }) {
schemaTypeInfo = new TypeInfo(schema);
},
onExecute({ args, setResultAndStopExecution }) {
const errors: GraphQLError[] = [];
const typeInfo = schemaTypeInfo || new TypeInfo(args.schema);
const validationContext = new ValidationContext(args.schema, args.document, typeInfo, e => {
errors.push(e);
});

const visitor = visitInParallel(options.rules.map(rule => rule(validationContext, args)));
visit(args.document, visitWithTypeInfo(typeInfo, visitor));

for (const rule of options.rules) {
rule(validationContext, args);
}

if (errors.length > 0) {
setResultAndStopExecution({
data: null,
errors,
});
}
},
};
};
27 changes: 27 additions & 0 deletions packages/plugins/extended-validation/src/rules/one-of.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { GraphQLInputObjectType, Kind } from 'graphql';
import { ExtendedValidationRule, getDirectiveFromType } from '../common';

export const ONE_OF_DIRECTIVE_SDL = /* GraphQL */ `
directive @oneOf on INPUT_OBJECT | FIELD_DEFINITION
`;

export const OneOfInputObjectsRule: ExtendedValidationRule = (context, executionArgs) => {
return {
Argument: node => {
if (node.value.kind === Kind.VARIABLE) {
const argType = context.getArgument().type as GraphQLInputObjectType;
const directive = getDirectiveFromType(argType, 'oneOf');

if (directive) {
const variableName = node.value.name.value;
const variableValue = (executionArgs.variableValues || {})[variableName];
const keys = Object.keys(variableValue);

if (keys.length !== 1) {
throw new Error(`Exactly one key must be specified for argument of type ${argType} (used in $${variableName})`);
}
}
}
},
};
};
53 changes: 53 additions & 0 deletions packages/plugins/extended-validation/test/one-of.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { buildSchema, validate } from 'graphql';
import { createTestkit } from '@envelop/testing';
import { useExtendedValidation, ONE_OF_DIRECTIVE_SDL, OneOfInputObjectsRule } from '../src';
import { Plugin } from '@envelop/types';

describe('useExtendedValidation', () => {
const testSchema = buildSchema(/* GraphQL */ `
${ONE_OF_DIRECTIVE_SDL}

type Query {
user(input: UserUniqueCondition): User
}

type User {
id: ID!
}

input UserUniqueCondition @oneOf {
id: ID
username: String
}
`);

it('Should throw an error when both fields are missing', async () => {
const testInstance = createTestkit(
[
useExtendedValidation({
rules: [OneOfInputObjectsRule],
}),
],
testSchema
);

const result = await testInstance.execute(
/* GraphQL */ `
query user($input: UserUniqueCondition!) {
user(input: $input) {
id
}
}
`,
{
input: {},
}
);

expect(result.errors).toBeDefined();
expect(result.errors.length).toBe(1);
expect(result.errors[0].message).toBe(
'Exactly one key must be specified for argument of type UserUniqueCondition (used in $input)'
);
});
});
9 changes: 7 additions & 2 deletions packages/testing/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ export function createTestkit(
pluginsOrEnvelop: Envelop | Plugin[],
schema?: GraphQLSchema
): {
execute: (operation: DocumentNode | string, initialContext?: any) => Promise<ExecutionResult<any>>;
execute: (
operation: DocumentNode | string,
variables?: Record<string, any>,
initialContext?: any
) => Promise<ExecutionResult<any>>;
replaceSchema: (schema: GraphQLSchema) => void;
wait: (ms: number) => Promise<void>;
} {
Expand All @@ -71,13 +75,14 @@ export function createTestkit(
return {
wait: ms => new Promise(resolve => setTimeout(resolve, ms)),
replaceSchema,
execute: async (operation, initialContext = null) => {
execute: async (operation, rawVariables = {}, initialContext = null) => {
const request = {
headers: {},
method: 'POST',
query: '',
body: {
query: typeof operation === 'string' ? operation : print(operation),
variables: rawVariables,
},
};
const proxy = initRequest();
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export interface Plugin<PluginContext = DefaultContext> {
executeFn: typeof execute;
args: ExecutionArgs;
setExecuteFn: (newExecute: typeof execute) => void;
setResultAndStopExecution: (newResult: ExecutionResult) => void;
extendContext: (contextExtension: Partial<PluginContext>) => void;
}) => void | OnExecuteHookResult<PluginContext>;
onSubscribe?: (options: {
Expand Down