forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphql.js
103 lines (85 loc) · 2.36 KB
/
graphql.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
import { ApolloServer, gql } from 'apollo-server-micro'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import { Photon } from '@generated/photon'
const photon = new Photon()
const JWT_SECRET = 'PleaseUseBetterStorageForThisSecret'
const getUserId = (req) => {
const Authorization = req.headers && req.headers.authorization ? req.headers.authorization : ''
if (Authorization) {
const token = Authorization.replace('Bearer ', '')
const verifiedToken = jwt.verify(token, JWT_SECRET)
return verifiedToken.userId
}
}
const typeDefs = gql`
type Query {
me: User!
}
type Mutation {
register(email: String, name: String, password: String): AuthPayload!
login(email: String, password: String): AuthPayload!
}
type AuthPayload {
token: String
}
type User {
id: String
name: String
email: String
}
`
const resolvers = {
Query: {
async me (parent, args, context) {
const id = context.user
const user = await context.photon.users.findOne({ where: { id } }).then(user => user)
if (!user) throw new Error('No such user found.')
return { ...user }
}
},
Mutation: {
async register (parent, { email, name, password }, context) {
const hashedPassword = await bcrypt.hash(password, 10)
const user = await context.photon.users.create({
data: {
email,
name,
password: hashedPassword
}
}).then(user => user)
if (!user) throw new Error('No such user found.')
const token = jwt.sign({
userId: user.id
}, JWT_SECRET)
return { token }
},
async login (parent, { email, password }, context) {
const user = await context.photon.users.findOne({ where: { email } }).then(user => user)
if (!user) throw new Error('No such user found.')
const valid = await bcrypt.compare(password, user.password)
if (valid) {
const token = jwt.sign({
userId: user.id
}, JWT_SECRET)
return { token }
} else {
throw new Error('Invalid password.')
}
}
}
}
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
const user = getUserId(req)
return { req, user, photon }
}
})
export const config = {
api: {
bodyParser: false
}
}
export default apolloServer.createHandler({ path: '/api/graphql' })