-
Notifications
You must be signed in to change notification settings - Fork 7
/
value-validation-directives.ts
351 lines (334 loc) · 8.06 KB
/
value-validation-directives.ts
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { gql } from 'graphql-tag';
import type { GraphQLResolveInfo } from 'graphql';
import { graphql, print } from 'graphql';
import {
listLength,
pattern,
range,
stringLength,
ValidateDirectiveVisitor,
trim,
applyDirectivesToSchema,
} from '../lib';
import type ValidationError from '../lib/errors/ValidationError.js';
interface ValidationErrorsResolverInfo extends GraphQLResolveInfo {
validationErrors?: ValidationError[];
}
const yourTypeDefs = [
gql`
# ValidatedInputErrorOutput and ValidatedInputError are defined by
# ValidateDirectiveVisitor.getMissingCommonTypeDefs()
type IntRangeExample {
arg: Int
validationErrors: [ValidatedInputErrorOutput!]
}
type FloatRangeExample {
arg: Int
validationErrors: [ValidatedInputErrorOutput!]
}
type PatternExample {
arg: String
validationErrors: [ValidatedInputErrorOutput!]
}
type StringLengthExample {
arg: String
validationErrors: [ValidatedInputErrorOutput!]
}
type ListLengthExample {
arg: [Int]
validationErrors: [ValidatedInputErrorOutput!]
}
type TrimExample {
arg: String
validationErrors: [ValidatedInputErrorOutput!]
}
type Query {
intRangeExample(arg: Int @range(min: -10, max: 10)): IntRangeExample
floatRangeExample(
arg: Float @range(min: -0.5, max: 0.5)
): FloatRangeExample
patternExample(
arg: String @pattern(regexp: "[a-z]+", flags: "i")
): PatternExample
stringLengthExample(
arg: String @stringLength(min: 1, max: 3)
): StringLengthExample
listLengthExample(
arg: [Int] @listLength(min: 1, max: 100)
): ListLengthExample
throwingIntRangeExample(
arg: Int @range(min: -10, max: 10, policy: THROW)
): IntRangeExample
trimExample(arg: String @trim(mode: TRIM_ALL)): TrimExample
}
`,
];
const argsResolver = (
_: unknown,
{ arg }: { arg: unknown },
__: unknown,
{ validationErrors }: ValidationErrorsResolverInfo,
): object => ({ arg, validationErrors });
const directives = [listLength, pattern, range, stringLength, trim];
const schema = applyDirectivesToSchema(
directives,
makeExecutableSchema({
resolvers: {
Query: {
floatRangeExample: argsResolver,
intRangeExample: argsResolver,
listLengthExample: argsResolver,
patternExample: argsResolver,
stringLengthExample: argsResolver,
throwingIntRangeExample: argsResolver,
trimExample: argsResolver,
},
},
typeDefs: [
...yourTypeDefs,
...ValidateDirectiveVisitor.getMissingCommonTypeDefs(),
...listLength.getTypeDefs(),
...pattern.getTypeDefs(),
...range.getTypeDefs(),
...stringLength.getTypeDefs(),
...trim.getTypeDefs(),
],
}),
);
// works as test and sample queries
const tests = {
AllInvalid: {
query: gql`
query AllInvalid {
floatRangeExample(arg: -1) {
arg
validationErrors {
message
path
}
}
intRangeExample(arg: 100) {
arg
validationErrors {
message
path
}
}
listLengthExample(arg: []) {
arg
validationErrors {
message
path
}
}
patternExample(arg: "12") {
arg
validationErrors {
message
path
}
}
stringLengthExample(arg: "hi there") {
arg
validationErrors {
message
path
}
}
}
`,
result: {
data: {
floatRangeExample: {
arg: null,
validationErrors: [
{
message: 'Less than -0.5',
path: ['arg'],
},
],
},
intRangeExample: {
arg: null,
validationErrors: [
{
message: 'More than 10',
path: ['arg'],
},
],
},
listLengthExample: {
arg: null,
validationErrors: [
{
message: 'List Length is Less than 1',
path: ['arg'],
},
],
},
patternExample: {
arg: null,
validationErrors: [
{
message: 'Does not match pattern: /[a-z]+/i',
path: ['arg'],
},
],
},
stringLengthExample: {
arg: null,
validationErrors: [
{
message: 'String Length is More than 3',
path: ['arg'],
},
],
},
},
},
},
AllValid: {
query: gql`
query AllValid {
floatRangeExample(arg: 0) {
arg
validationErrors {
message
path
}
}
intRangeExample(arg: 1) {
arg
validationErrors {
message
path
}
}
listLengthExample(arg: [1, 2]) {
arg
validationErrors {
message
path
}
}
patternExample(arg: "hello") {
arg
validationErrors {
message
path
}
}
stringLengthExample(arg: "hi") {
arg
validationErrors {
message
path
}
}
trimExample(arg: ${JSON.stringify(
' \t \r \n \r\n trimmed! \n\n \t \r\n',
)}){
arg
validationErrors {
message
path
}
}
}
`,
result: {
data: {
floatRangeExample: {
arg: 0,
validationErrors: null,
},
intRangeExample: {
arg: 1,
validationErrors: null,
},
listLengthExample: {
arg: [1, 2],
validationErrors: null,
},
patternExample: {
arg: 'hello',
validationErrors: null,
},
stringLengthExample: {
arg: 'hi',
validationErrors: null,
},
trimExample: {
arg: 'trimmed!',
validationErrors: null,
},
},
},
},
Throwing: {
query: gql`
query Throwing {
throwingIntRangeExample(arg: 100) {
arg
validationErrors {
message
path
}
}
}
`,
result: {
// keep same order as in GQL so JSON.stringify() serializes the same
/* eslint-disable sort-keys */
errors: [
{
message: 'More than 10',
locations: [
{
line: 2,
column: 3,
},
],
path: ['throwingIntRangeExample'],
extensions: {
code: 'GRAPHQL_VALIDATION_FAILED',
validation: {
path: ['arg'],
},
},
},
],
data: {
throwingIntRangeExample: null,
},
},
/* eslint-enable sort-keys */
},
};
const test = async (): Promise<void[]> =>
Promise.all(
Object.entries(tests).map(
async ([name, { query, result: expected }]): Promise<void> => {
const source = print(query);
const result = await graphql({ schema, source });
if (JSON.stringify(result) !== JSON.stringify(expected)) {
throw Error(`test ${name} failed`);
}
// eslint-disable-next-line no-console
console.log(`✅ test ${name} works:\n${source}\n`);
},
),
);
test().catch(error => {
// eslint-disable-next-line no-console
console.error('💥test queries failed:', error);
process.exit(1);
});
const server = new ApolloServer({ schema });
startStandaloneServer(server).then(({ url }) => {
// eslint-disable-next-line no-console
console.log(`🚀 Server ready at ${url}`);
});