-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
140 lines (130 loc) · 2.88 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
const { ApolloServer, gql } = require('apollo-server');
let employees = [
{
id: 1,
name: 'John Smith',
employerId: 1,
},
{
id: 2,
name: 'Lauren Armstrong',
employerId: 1,
},
{
id: 3,
name: 'Henry Bautista',
employerId: 1,
},
{
id: 4,
name: 'Jake Snarl',
employerId: 2,
},
];
let employers = [
{
id: 1,
name: 'Harrys pub',
},
{
id: 2,
name: 'UPS',
},
];
const typeDefs = gql`
type Query {
employers: [Employer]
employees: [Employee]
employer(id: Int): Employer
employee(id: Int): Employee
}
type Employer {
id: Int
name: String
employees: [Employee]
numEmployees: Int
}
type Employee {
id: Int
name: String
employer: Employer
}
type Mutation {
addEmployee(name: String!, employerId: Int!): Employee
removeEmployee(id: Int!): [Employee]
changeEmployeeName(id: Int!, name: String!): Employee
changeEmployer(id: Int!, employerId: Int!): Employee
}
`;
const resolvers = {
Query: {
employer: (_, args) => employers.filter(e => e.id === args.id)[0],
employee: (_, args) => employees.filter(e => e.id === args.id)[0],
employers: () => employers,
employees: () => employees,
},
Employer: {
numEmployees: (parentValue) => {
console.log('parentValue in Employer: ', parentValue);
return employees.filter(e => e.employerId === parentValue.id).length;
},
employees: (parentValue) => {
return employees.filter(e => e.employerId === parentValue.id);
},
},
Employee: {
employer: (parentValue) => {
return employers.filter(e => e.id === parentValue.employerId)[0];
},
},
Mutation: {
addEmployee: (_, args) => {
const newEmployee = {
id: employees.length + 1,
name: args.name,
employerId: args.employerId,
};
employees.push(newEmployee);
return newEmployee;
},
removeEmployee: (_, args) => {
return employees.filter(e => e.id !== args.id)
},
changeEmployeeName: (_, args) => {
let newEmployee;
// Change employees
employees = employees.map(e => {
if(e.id === args.id) {
newEmployee = {
...e,
name: args.name,
};
return newEmployee
};
return e;
});
// Return change employee
return newEmployee;
},
changeEmployer: (_, args) => {
let newEmployee;
// Change employees
employees = employees.map(e => {
if(e.id === args.id) {
newEmployee = {
...e,
employerId: args.employerId,
};
return newEmployee
};
return e;
});
// Return change employee
return newEmployee;
},
}
}
const server = new ApolloServer({ typeDefs, resolvers })
server.listen().then(({ url }) => {
console.log(`Server is ready at ${url}`)
});