| 1 | import type { ApolloServerPlugin } from '@apollo/server'; |
| 2 | import { |
| 3 | GraphQLError, |
| 4 | OverlappingFieldsCanBeMergedRule, |
| 5 | specifiedRules, |
| 6 | validate, |
| 7 | type ValidationContext, |
| 8 | type ValidationRule, |
| 9 | } from 'graphql'; |
| 10 | |
| 11 | const TYPE_CONFLICT = / |
| 12 | const OTHER_CONFLICT = |
| 13 | /are different fields|differing arguments|differing stream directives/; |
| 14 | |
| 15 | /** GitHub accepts one response name with different types in fragments that cannot both apply (gh selects `state` on both Issue and PullRequest); graphql-js refuses it. Every other overlap stays refused. */ |
| 16 | const OverlappingFieldsAsOnGitHubRule: |
| 17 | OverlappingFieldsCanBeMergedRule( |
| 18 | Object.create(context |
| 19 | reportError: { |
| 20 | value: (error: |
| 21 | if ( |
| 22 | TYPE_CONFLICT.test(error |
| 23 | !OTHER_CONFLICT.test(error |
| 24 | ) |
| 25 | return; |
| 26 | context.reportError(error |
| 27 | }, |
| 28 | }, |
| 29 | }) as ValidationContext |
| 30 | ); |
| 31 | |
| 32 | export const githubValidationRules = |
| 33 | rule === OverlappingFieldsCanBeMergedRule |
| 34 | ? OverlappingFieldsAsOnGitHubRule |
| 35 | : rule, |
| 36 | ); |
| 37 | |
| 38 | /** Validates with githubValidationRules in Apollo's place; Apollo's own validation must be off (`dangerouslyDisableValidation`). Answers the first error with 400, as Apollo's validation does. */ |
| 39 | export const githubValidationPlugin: |
| 40 | async requestDidStart() { |
| 41 | return { |
| 42 | async didResolveOperation({ |
| 43 | const [error] |
| 44 | if (error) |
| 45 | throw new GraphQLError( |
| 46 | nodes: error.nodes |
| 47 | extensions: { |
| 48 | code: 'GRAPHQL_VALIDATION_FAILED', |
| 49 | http: { status: 400 |
| 50 | }, |
| 51 | }); |
| 52 | }, |
| 53 | }; |
| 54 | }, |
| 55 | }; |