-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMutation.ts
executable file
·101 lines (96 loc) · 2.44 KB
/
Mutation.ts
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
import { compare, hash } from 'bcrypt'
import { sign } from 'jsonwebtoken'
import { idArg, mutationType, stringArg } from 'nexus'
import { APP_SECRET, getUserId } from '../utils'
export const Mutation = mutationType({
definition(t) {
t.field('signup', {
type: 'AuthPayload',
args: {
name: stringArg({ nullable: true }),
email: stringArg(),
password: stringArg(),
},
resolve: async (parent, { name, email, password }, ctx) => {
const hashedPassword = await hash(password, 10)
const user = await ctx.photon.users.create({
data: {
name,
email,
password: hashedPassword,
},
})
return {
token: sign({ userId: user.id }, APP_SECRET),
user,
}
},
})
t.field('login', {
type: 'AuthPayload',
args: {
email: stringArg(),
password: stringArg(),
},
resolve: async (parent, { email, password }, context) => {
const user = await context.photon.users.findOne({
where: {
email,
},
})
if (!user) {
throw new Error(`No user found for email: ${email}`)
}
const passwordValid = await compare(password, user.password)
if (!passwordValid) {
throw new Error('Invalid password')
}
return {
token: sign({ userId: user.id }, APP_SECRET),
user,
}
},
})
t.field('createDraft', {
type: 'Post',
args: {
title: stringArg(),
content: stringArg({ nullable: true }),
},
resolve: (parent, { title, content }, ctx) => {
const userId = getUserId(ctx)
return ctx.photon.posts.create({
data: {
title,
content,
published: false,
author: { connect: { id: userId } },
},
})
},
})
t.field('deletePost', {
type: 'Post',
nullable: true,
args: { id: idArg() },
resolve: (parent, { id }, ctx) => {
return ctx.photon.posts.delete({
where: {
id,
},
})
},
})
t.field('publish', {
type: 'Post',
nullable: true,
args: { id: idArg() },
resolve: (parent, { id }, ctx) => {
return ctx.photon.posts.update({
where: { id },
data: { published: true },
})
},
})
},
})