-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
110 lines (97 loc) · 2.25 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
import { ApolloServer, gql, UserInputError } from "apollo-server";
import { v1 as uuid } from "uuid";
const persons = [
{
name: "Alejandro",
phone: "3364012345",
street: "J. J. Pastor",
city: "La Emilia",
id: "00000000001",
},
{
name: "Facundo",
phone: "3364112211",
street: "Av. Siempre Viva",
city: "La Emilia",
id: "00000000002",
},
{
name: "Melisa",
street: "24 de abril",
city: "La Emilia",
id: "00000000003",
},
];
const typeDefs = gql`
enum YesNo {
YES
NO
}
type Address {
street: String!
city: String!
}
type Person {
name: String!
phone: String
address: Address!
id: ID!
}
type Query {
personCount: Int!
allPersons(phone: YesNo): [Person]!
findPerson(name: String!): Person
}
type Mutation {
addPerson(
name: String!
phone: String
street: String!
city: String!
): Person
editPhone(name: String!, phone: String!): Person
}
`;
const resolvers = {
Query: {
personCount: () => persons.length,
allPersons: (root, args) => {
if (!args.phone) return persons;
return persons.filter((person) => {
return args.phone === "YES" ? person.phone : !person.phone;
});
},
findPerson: (root, args) => {
const { name } = args;
return persons.find((person) => person.name === name);
},
},
Mutation: {
addPerson: (root, args) => {
if (persons.find((p) => p.name === args.name)) {
throw new UserInputError("Name must be unique");
}
const person = { ...args, id: uuid() };
persons.push(person); //update database
return person;
},
editPhone: (root, args) => {
const personIndex = persons.findIndex((p) => p.name === args.name);
if (personIndex === -1) return null;
const person = persons[personIndex];
const updatedPerson = { ...person, phone: args.phone };
persons[personIndex] = updatedPerson;
return updatedPerson;
},
},
Person: {
address: (root) => {
return {
street: root.street,
city: root.city,
};
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => console.log(`Server ready at ${url}`));