-
Notifications
You must be signed in to change notification settings - Fork 8
/
schema.ts
126 lines (120 loc) 路 2.8 KB
/
schema.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
import {
stringArg,
makeSchema,
mutationType,
objectType,
intArg,
queryType,
} from 'nexus';
import { validatePlugin, ValidationError } from 'nexus-validate';
import { UserInputError } from 'apollo-server';
let USERS = [
{
name: 'Test',
email: 'test@test.com',
age: 30,
website: 'https://website.com',
},
];
export const User = objectType({
name: 'User',
definition(t) {
t.string('name');
t.string('email');
t.int('age');
t.string('website');
t.string('secret');
t.list.field('friends', {
type: User,
args: {
email: stringArg(),
},
validate: ({ string }) => ({
email: string().email(),
}),
resolve: (_, args) => {
return USERS;
},
});
},
});
const Mutation = mutationType({
definition(t) {
t.field('createUser', {
type: 'User',
args: {
name: stringArg(),
email: stringArg(),
age: intArg(),
website: stringArg(),
secret: stringArg(),
},
// this will get called before the resolver and we can use
// the rules from the first argument together with args and context
// to figure out if the provided arguments are valid or not
validate: ({ string, number }, args, ctx) => ({
name: string().trim(),
email: string().email().trim(),
age: number().min(18),
website: string().url(),
// create a custom rule for secret that uses a custom test,
// the provided argument and the graphql context
secret: string().test(
'valid-secret',
`${args.secret} is not the correct secret`,
(value) => value === ctx.secret
),
}),
resolve: (_, args) => {
return {
...USERS[0],
...args,
};
},
});
},
});
const Query = queryType({
definition(t) {
t.field('user', {
type: 'User',
args: {
email: stringArg(),
},
validate: ({ string }, args, ctx) => ({
email: string().email(),
}),
resolve: (_, args) => {
return {
...USERS[0],
...args,
};
},
});
},
});
export const schema = makeSchema({
types: [User, Mutation, Query],
contextType: {
module: require.resolve('./context'),
export: 'Context',
},
outputs: {
schema: __dirname + '/../schema.graphql',
typegen: __dirname + '/generated/nexus.ts',
},
// add the plugin with a custom `formatError` function
// that passed the error to apollos UserInputError
plugins: [
validatePlugin({
formatError: ({ error }) => {
if (error instanceof ValidationError) {
return new UserInputError(error.message, {
invalidArgs: [error.path],
});
}
return error;
},
}),
],
});