-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
apollo4.js
72 lines (66 loc) · 2.09 KB
/
apollo4.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const {
separateOperations,
buildSchema,
GraphQLError
} = require('graphql')
const { constraintDirectiveTypeDefs } = require('./lib/type-defs')
const { gql } = require('graphql-tag')
const { validateQuery } = require('./lib/validate-query')
let currentSchema
function createApollo4QueryValidationPlugin (options = {}) {
return {
async serverWillStart () {
return {
schemaDidLoadOrUpdate ({ apiSchema, coreSupergraphSdl }) {
if (coreSupergraphSdl) { currentSchema = buildSchema(coreSupergraphSdl) } else { currentSchema = apiSchema }
}
}
},
async requestDidStart () {
return ({
async didResolveOperation (requestContext) {
const { request, document } = requestContext
const query = request.operationName
? separateOperations(document)[request.operationName]
: document
const errors = validateQuery(
currentSchema,
query,
request.variables,
request.operationName,
options
)
if (errors.length > 0) {
const te = errors.map(err => {
return new GraphQLError(err.message, {
extensions: {
field: err.fieldName,
context: err.context,
code: 'BAD_USER_INPUT',
http: {
status: 400
}
}
})
})
if (te.length === 1) {
throw te[0]
} else {
throw new GraphQLError('Query is invalid, for details see extensions.validationErrors', {
extensions: {
code: 'BAD_USER_INPUT',
validationErrors: te,
http: {
status: 400
}
}
})
}
}
}
})
}
}
}
const constraintDirectiveTypeDefsGql = gql(constraintDirectiveTypeDefs)
module.exports = { constraintDirectiveTypeDefs, constraintDirectiveTypeDefsGql, createApollo4QueryValidationPlugin }