-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.js
More file actions
107 lines (94 loc) · 2.08 KB
/
Copy pathschema.js
File metadata and controls
107 lines (94 loc) · 2.08 KB
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
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLList
} = require("graphql");
const users = [
{ id: 1, firstName: 'Tom', lastName: 'Smith' },
{ id: 2, firstName: 'Anna', lastName: 'Jones' },
];
const posts = [
{ id: 1, userId: 1, title: 'Hello', votes: 2 },
{ id: 2, userId: 2, title: 'GraphQL', votes: 3 },
];
let getUser = id => users.find(user => user.id === id);
let getPost = id => posts.find(post => post.id === id);
let getPosts = userId => (userId ? posts.filter(post => post.userId === userId) : posts);
const PostType = new GraphQLObjectType({
name: "Post",
description: "...",
fields: () => ({
id: { type: GraphQLInt },
user: {
type: UserType,
resolve(parent, args) {
return getUser(parent.userId)
}
},
title: { type: GraphQLString },
votes: { type: GraphQLInt }
})
});
const UserType = new GraphQLObjectType({
name: "User",
description: "...",
fields: {
id: { type: GraphQLInt },
firstName: { type: GraphQLString },
lastName: { type: GraphQLString },
posts: {
type: new GraphQLList(PostType),
resolve(parent, args) {
return getPosts(parent.id)
}
}
}
})
const queryFields = {
user: {
type: UserType,
args: {
id: { type: GraphQLInt }
},
resolve(parent, args) {
return getUser(args.id);
}
},
posts: {
type: new GraphQLList(PostType),
resolve: getPosts
}
}
const mutationFields = {
upvotePost: {
type: PostType,
args: {
id: { type: GraphQLInt }
},
resolve(parent, args) {
const post = getPost(args.id);
if (!post) {
throw new Error("No posts with id '${postId}'");
}
post.votes += 1;
return post;
}
}
}
const QueryType = new GraphQLObjectType({
name: "Query",
description: "...",
fields: queryFields
});
const MutationType = new GraphQLObjectType({
name: "Mutation",
description: "...",
fields: mutationFields
});
const schema = new GraphQLSchema({
query: QueryType,
mutation: MutationType
});
module.exports = schema;