-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
215 lines (203 loc) · 6 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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
const { ApolloServer, gql, UserInputError, AuthenticationError, PubSub } = require('apollo-server')
const { v4: uuidv4 } = require('uuid');
const mongoose = require('mongoose')
const Author = require('./models/Author')
const Book = require('./models/Book')
const User = require('./models/User')
const jwt = require('jsonwebtoken')
const pubsub = new PubSub();
require('dotenv').config()
console.log('connecting to', process.env.MONGO_URI)
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true })
.then(() => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connection to MongoDB:', error.message)
})
const typeDefs = gql`
type Subscription {
bookAdded: Book
}
type Query {
bookCount: Int!
authorCount: Int!
allBooks(name: String, genre: String): [Book!]!
allAuthors: [Author!]!
me: User
}
type User {
username: String!
favoriteGenre: String!
id: ID!
}
type Token {
value: String!
}
type Author {
name: String!
born: Int
bookCount: Int!
}
type Book {
title: String!
published: Int!
author: Author
id: ID!
genres: [String]!
}
type Mutation {
addBook(
title: String!
published: Int!
author: String!
genres: [String]!
) : Book
editAuthor(
name: String!
setBornTo: Int!
) : Author
createUser(
username: String!
favoriteGenre: String!
): User
login(
username: String!
password: String!
): Token
}
`
const resolvers = {
Subscription: {
bookAdded: {
subscribe: () => pubsub.asyncIterator(['BOOK_ADDED']),
}
},
Query: {
bookCount: () => Book.collection.countDocuments(),
authorCount: () => Author.collection.countDocuments(),
allBooks: async (root, args, {currentUser}) => {
if (args.name && args.genre) {
return books.filter(book => book.author === args.name)
.filter(book => book.genres.includes(args.genre))
} else if (args.name) {
return books.filter(book => book.author === args.name)
} else if (args.genre) {
return Book.find({genres: {$in : args.genre}}).populate('author')
} else {
return Book.find({}).populate('author')
}
},
allAuthors: () => Author.find({}),
me: (root, args, {currentUser}) => currentUser
},
Author: {
bookCount: async (root) => {
const books = await Book.find({}).populate('author')
return books.filter(b => b.author.name === root.name).length
}
},
Book: {
author: async (root) => {
const b = await Book.findOne({title : root.title}).populate('author')
const authorFound = await Author.findOne({name: b.author.name})
authorFound ? console.log(`test ${authorFound}`) : console.log(`no auth`)
return {
name: authorFound.name,
born: authorFound.born
}
}
},
Mutation: {
createUser: async (root, args) => {
const user = new User({
username: args.username,
favoriteGenre: args.favoriteGenre
})
try {
await user.save()
} catch (e) {
throw new UserInputError(e.message, {
invalidArgs: args,
})
}
return user
},
login: async (root, args) => {
const user = await User.findOne({ username: args.username })
if ( !user || args.password !== 'cheese' ) {
throw new UserInputError("wrong credentials")
}
const userForToken = {
username: user.username,
id: user._id,
}
return { value: jwt.sign(userForToken, process.env.SECRET) }
},
addBook: async (root, args, {currentUser}) => {
if (!currentUser) {
throw new AuthenticationError("not authenticated")
}
let author = await Author.find({name: args.author})
let authorId
if (!author[0]) {
console.log(`author is undefined`)
const newAuthor = new Author({name: args.author})
try {
author = await newAuthor.save()
} catch (e) {
throw new UserInputError(e.message, {
invalidArgs: args,
})
}
authorId = author._id
} else {
authorId = author[0]._id
}
const newBook = new Book({title: args.title, published: args.published, genres: args.genres, author: authorId})
console.log(newBook)
try {
await newBook.save()
pubsub.publish(`BOOK_ADDED`, {bookAdded: newBook})
} catch (e) {
throw new UserInputError(e.message, {
invalidArgs: args,
})
}
return newBook
},
editAuthor: async (root, args, {currentUser}) => {
if (!currentUser) {
throw new AuthenticationError("not authenticated")
}
const authorFound = await Author.findOne({name: args.name})
authorFound.born = args.setBornTo
try {
await authorFound.save()
} catch (error) {
throw new UserInputError(error.message, {
invalidArgs: args,
})
}
return authorFound
}
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
cors: {origin: '*', // <- allow request from all domains
credentials: true},
context: async ({ req }) => {
const auth = req ? req.headers.authorization : null
if (auth && auth.toLowerCase().startsWith('bearer ')) {
const decodedToken = jwt.verify(auth.substring(7), process.env.SECRET)
const currentUser = await User.findById(decodedToken.id)
return { currentUser }
}
}
})
server.listen().then(({ url, subscriptionsUrl }) => {
console.log(`Server ready at ${url}`)
console.log(`Sub url at ${subscriptionsUrl}`)
})