-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
124 lines (102 loc) · 1.87 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
const { graphql } = require('graphql')
const { makeExecutableSchema } = require('graphql-tools')
/**
* SAMPLE DATA
*/
const post1 = {
id: 'post-1',
title: 'My first post',
author: '123',
}
const posts = [post1]
const users = [
{
id: 'user-1',
username: 'nikolas',
posts: [post1],
},
]
/**
* SCHEMA DEFINITION (SDL)
*/
const typeDefs = `
type User {
id: ID!
username: String!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
author: User!
}
type Query {
author(id: ID!): User!
feed: [Post!]!
}
`
/**
* RESOLVERS
*/
const resolvers = {
Query: {
author: (root, { id }, context, info) => {
console.log(`Query.author - info: `, JSON.stringify(info))
return users.find(u => u.id === id)
},
feed: (root, args, context, info) => {
console.log(`Query.feed - info: `, JSON.stringify(info))
return posts
},
},
Post: {
// this actually not required as graphql-js can infer the value
title: (root, args, context, info) => {
console.log(`Post.title - info: `, JSON.stringify(info))
return root.title
},
},
}
/**
* QUERY
*/
// without variables
// const queryString = `
// query AuthorWithPosts {
// author(id: "user-1") {
// username
// posts {
// id
// title
// }
// }
// }
// `
// with variables
const queryString = `
query AuthorWithPosts($userId: ID!) {
author(id: $userId) {
username
posts {
id
title
}
}
}
`
const variables = { userId: 'user-1' }
/**
* EXECUTION
*/
const executableSchema = makeExecutableSchema({
typeDefs,
resolvers,
})
// without variables
// graphql(executableSchema, queryString, null, null).then(result =>
// console.log(JSON.stringify(result)),
// )
// with variables
graphql(executableSchema, queryString, null, null, variables).then(result =>
console.log(JSON.stringify(result)),
)