@@ -42,22 +42,58 @@ export const webhookRouter = createProtectedRouter()
42
42
eventTypeId : z . number ( ) . optional ( ) ,
43
43
appId : z . string ( ) . optional ( ) . nullable ( ) ,
44
44
} ) ,
45
- async resolve ( { ctx, input } ) {
46
- if ( input . eventTypeId ) {
47
- return await ctx . prisma . webhook . create ( {
48
- data : {
49
- id : v4 ( ) ,
50
- ...input ,
51
- } ,
45
+ async resolve ( { ctx, input : { eventTypeId, ...input } } ) {
46
+ const webhookCreateInput : Prisma . WebhookCreateInput = {
47
+ id : v4 ( ) ,
48
+ ...input ,
49
+ } ;
50
+ const webhookPayload = { webhooks : { create : webhookCreateInput } } ;
51
+ let teamId = - 1 ;
52
+ if ( eventTypeId ) {
53
+ /* [1] If an eventType is provided, we find the team were it belongs */
54
+ const team = await ctx . prisma . team . findFirst ( {
55
+ rejectOnNotFound : true ,
56
+ where : { eventTypes : { some : { id : eventTypeId } } } ,
57
+ select : { id : true } ,
52
58
} ) ;
59
+ /* [2] We save the id for later use */
60
+ teamId = team . id ;
53
61
}
54
- return await ctx . prisma . webhook . create ( {
55
- data : {
56
- id : v4 ( ) ,
57
- userId : ctx . user . id ,
58
- ...input ,
59
- } ,
62
+ await ctx . prisma . user . update ( {
63
+ where : { id : ctx . user . id } ,
64
+ /**
65
+ * [3] Right now only team eventTypes can have webhooks so we make sure the
66
+ * user adding the webhook belongs to the team.
67
+ */
68
+ data : eventTypeId
69
+ ? {
70
+ teams : {
71
+ update : {
72
+ /* [3.1] Here we make sure the requesting user belongs to the team */
73
+ where : { userId_teamId : { teamId, userId : ctx . user . id } } ,
74
+ data : {
75
+ team : {
76
+ update : {
77
+ eventTypes : {
78
+ update : {
79
+ where : { id : eventTypeId } ,
80
+ data : webhookPayload ,
81
+ } ,
82
+ } ,
83
+ } ,
84
+ } ,
85
+ } ,
86
+ } ,
87
+ } ,
88
+ }
89
+ : /* [4] If there's no eventTypeId we create it to the current user instead. */
90
+ webhookPayload ,
91
+ } ) ;
92
+ const webhook = await ctx . prisma . webhook . findUnique ( {
93
+ rejectOnNotFound : true ,
94
+ where : { id : webhookCreateInput . id } ,
60
95
} ) ;
96
+ return webhook ;
61
97
} ,
62
98
} )
63
99
. mutation ( "edit" , {
0 commit comments