-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (76 loc) · 1.78 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
const { GraphQLServer } = require('graphql-yoga');
let count = 2;
let todos = [{
id: '0',
content: 'Buy milk',
isCompleted: true
},
{
id: '1',
content: 'Cook some lobster',
isCompleted: false
}];
const resolvers = {
Query: {
allTodos: () => {
return todos;
},
Todo: (_, { id }) => {
const todo = todos.find(x => x.id === id);
if (!todo) {
throw new Error('Cannot find your todo!');
}
return todo;
}
},
Mutation: {
createTodo: (_, { content, isCompleted }) => {
const newTodo = {
id: count++,
content,
isCompleted
}
todos = [...todos, newTodo];
return newTodo;
},
updateTodo: (_, { id, content, isCompleted }) => {
let updatedTodo;
todos = todos.map(todo => {
if (todo.id === id) {
updatedTodo = {
id: todo.id,
// for content and isCompleted, we first check if values are provided
content: content !== undefined ? content : todo.content,
isCompleted: isCompleted !== undefined ? isCompleted : todo.isCompleted
}
return updatedTodo;
} else {
return todo
}
});
return updatedTodo;
},
deleteTodo: (_, { id }) => {
const todoToDelete = todos.find(x => x.id === id);
todos = todos.filter(todo => {
return todo.id !== todoToDelete.id;
});
return todoToDelete;
}
}
}
const options = {
port: 3333,
endpoint: '/graphql',
subscriptions: '/subscriptions',
playground: '/playground',
}
const server = new GraphQLServer({
typeDefs: './src/schema.graphql',
resolvers
})
server.start(options, ({ port }) =>
console.log(
`Server started, listening on port ${port} for incoming requests.`,
),
)