forked from confuser/graphql-constraint-directive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
162 lines (144 loc) · 5.08 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
const {
GraphQLNonNull,
GraphQLList,
TypeInfo,
ValidationContext,
visit,
visitWithTypeInfo,
separateOperations,
GraphQLError
} = require('graphql')
const QueryValidationVisitor = require('./lib/query-validation-visitor.js')
const { getDirective, mapSchema, MapperKind } = require('@graphql-tools/utils')
const { getConstraintTypeObject, getScalarType } = require('./lib/type-utils')
const { constraintDirectiveTypeDefs } = require('./lib/type-defs')
function constraintDirective () {
const constraintTypes = {}
function getConstraintType (fieldName, type, notNull, directiveArgumentMap, list, listNotNull) {
// Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ as per graphql-js
let uniqueTypeName
if (directiveArgumentMap.uniqueTypeName) {
uniqueTypeName = directiveArgumentMap.uniqueTypeName.replace(/\W/g, '')
} else {
uniqueTypeName =
`${fieldName}_${list ? 'List_' : ''}${listNotNull ? 'ListNotNull_' : ''}${
type.name
}_${notNull ? 'NotNull_' : ''}` +
Object.entries(directiveArgumentMap)
.map(([key, value]) => {
if (
key === 'min' ||
key === 'max' ||
key === 'exclusiveMin' ||
key === 'exclusiveMax' ||
key === 'multipleOf'
) {
return `${key}_${value.toString().replace(/\W/g, 'dot')}`
}
return `${key}_${value.toString().replace(/\W/g, '')}`
})
.join('_')
}
const key = Symbol.for(uniqueTypeName)
let constraintType = constraintTypes[key]
if (constraintType) return constraintType
constraintType = getConstraintTypeObject(fieldName, type, uniqueTypeName, directiveArgumentMap)
if (notNull) {
constraintType = new GraphQLNonNull(constraintType)
}
if (list) {
constraintType = new GraphQLList(constraintType)
if (listNotNull) {
constraintType = new GraphQLNonNull(constraintType)
}
}
constraintTypes[key] = constraintType
return constraintType
}
function wrapType (fieldConfig, directiveArgumentMap) {
const result = getScalarType(fieldConfig.type)
const fieldName = fieldConfig.astNode.name.value
fieldConfig.type = getConstraintType(
fieldName,
result.scalarType,
result.scalarNotNull,
directiveArgumentMap,
result.list,
result.listNotNull
)
}
return (schema) =>
mapSchema(schema, {
[MapperKind.FIELD]: (fieldConfig) => {
const directiveArgumentMap = getDirective(schema, fieldConfig, 'constraint')?.[0]
if (directiveArgumentMap) {
wrapType(fieldConfig, directiveArgumentMap)
return fieldConfig
}
},
[MapperKind.ARGUMENT]: (fieldConfig) => {
const directiveArgumentMap = getDirective(schema, fieldConfig, 'constraint')?.[0]
if (directiveArgumentMap) {
wrapType(fieldConfig, directiveArgumentMap)
return fieldConfig
}
}
})
}
function validateQuery (schema, query, variables, operationName) {
const typeInfo = new TypeInfo(schema)
const errors = []
const context = new ValidationContext(
schema,
query,
typeInfo,
(error) => errors.push(error)
)
const visitor = new QueryValidationVisitor(context, {
variables,
operationName
})
visit(query, visitWithTypeInfo(typeInfo, visitor))
return errors
}
function createApolloQueryValidationPlugin ({ schema }) {
return {
async requestDidStart () {
return ({
async didResolveOperation ({ request, document }) {
const query = request.operationName
? separateOperations(document)[request.operationName]
: document
const errors = validateQuery(
schema,
query,
request.variables,
request.operationName
)
if (errors.length > 0) {
throw errors.map(err => {
const { UserInputError } = require('apollo-server-errors')
return new UserInputError(err.message, { field: err.fieldName, context: err.context })
})
}
}
})
}
}
}
function createEnvelopQueryValidationPlugin () {
return {
onExecute ({ args, setResultAndStopExecution }) {
const errors = validateQuery(args.schema, args.document, args.variableValues, args.operationName)
if (errors.length > 0) {
setResultAndStopExecution({ errors: errors.map(err => { return new GraphQLError(err.message, null, null, null, null, err, { code: err.code, field: err.fieldName, context: err.context, exception: err.originalError }) }) })
}
}
}
}
function createQueryValidationRule (options) {
return (context) => {
return new QueryValidationVisitor(context, options)
}
}
module.exports = { constraintDirective, constraintDirectiveTypeDefs, validateQuery, createApolloQueryValidationPlugin, createEnvelopQueryValidationPlugin, createQueryValidationRule }