-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposts.ts
More file actions
185 lines (157 loc) · 5.08 KB
/
posts.ts
File metadata and controls
185 lines (157 loc) · 5.08 KB
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
'use client'
import { useMutation } from '@tanstack/react-query'
import type {
DeletePostMutationInput,
ReorderPostsMutationInput,
SavePostMutationInput
} from '@/types/mutations'
import type { Post, PostMedia } from '@/types/post'
import {
supabaseStorageBucketPosts,
supabaseStorageCacheControlPosts,
supabaseTablePostMedia,
supabaseTablePosts
} from '@/constants/db'
import { extensionForPostMediaUpload } from '@/utils/post-media'
import { extractPostsBucketObjectPath, removePostFolderObjects } from '@/utils/post-storage'
import { createClient } from '@/utils/supabase-browser'
async function savePostMutationFn(vars: SavePostMutationInput): Promise<Post> {
const supabase = createClient()
const { isEditing, post, profileId, nextPosition, caption, subtitle, status, mediaItems } = vars
let postId = post?.id
let postData: Post
if (isEditing && postId) {
const { data, error: updateError } = await supabase
.from(supabaseTablePosts)
.update({
caption: caption || null,
subtitle: subtitle || null,
status,
updated_at: new Date().toISOString()
})
.eq('id', postId)
.select()
.single()
if (updateError) throw updateError
postData = data as unknown as Post
} else {
const { data, error: insertError } = await supabase
.from(supabaseTablePosts)
.insert({
profile_id: profileId,
caption: caption || null,
subtitle: subtitle || null,
grid_position: nextPosition,
status: 'draft'
})
.select()
.single()
if (insertError) throw insertError
postId = data.id
postData = data as unknown as Post
}
if (!postId) {
throw new Error('Missing post id')
}
const uploadedMedia: PostMedia[] = []
if (isEditing && post) {
const currentIds = new Set(mediaItems.filter((m) => !m.isNew).map((m) => m.id))
const toDelete = post.media.filter((m) => !currentIds.has(m.id))
for (const media of toDelete) {
const path = extractPostsBucketObjectPath(media.media_url)
if (path) {
await supabase.storage.from(supabaseStorageBucketPosts).remove([path])
}
await supabase.from(supabaseTablePostMedia).delete().eq('id', media.id)
}
}
for (let i = 0; i < mediaItems.length; i++) {
const item = mediaItems[i]
if (item.isNew && item.file) {
const ext = extensionForPostMediaUpload(item.file)
const filePath = `${profileId}/${postId}/${crypto.randomUUID()}.${ext}`
const { error: uploadError } = await supabase.storage
.from(supabaseStorageBucketPosts)
.upload(filePath, item.file, {
cacheControl: supabaseStorageCacheControlPosts,
upsert: false,
contentType: item.file.type || undefined
})
if (uploadError) throw uploadError
const { data: urlData } = supabase.storage
.from(supabaseStorageBucketPosts)
.getPublicUrl(filePath)
const { data: mediaData, error: mediaError } = await supabase
.from(supabaseTablePostMedia)
.insert({
post_id: postId,
media_url: urlData.publicUrl,
media_type: item.type,
position: i
})
.select()
.single()
if (mediaError) throw mediaError
uploadedMedia.push(mediaData as PostMedia)
} else {
const { data: mediaData, error: updateError } = await supabase
.from(supabaseTablePostMedia)
.update({ position: i })
.eq('id', item.id)
.select()
.single()
if (updateError) throw updateError
uploadedMedia.push(mediaData as PostMedia)
}
}
postData.media = uploadedMedia
return postData
}
function useSavePostMutation() {
return useMutation({
mutationFn: savePostMutationFn
})
}
async function deletePostMutationFn(vars: DeletePostMutationInput): Promise<void> {
const supabase = createClient()
const { post, profileId } = vars
const paths = new Set<string>()
for (const media of post.media) {
const path = extractPostsBucketObjectPath(media.media_url)
if (path) paths.add(path)
}
if (paths.size > 0) {
await supabase.storage.from(supabaseStorageBucketPosts).remove([...paths])
}
await removePostFolderObjects(supabase, profileId, post.id)
const { error } = await supabase.from(supabaseTablePosts).delete().eq('id', post.id)
if (error) throw error
}
function useDeletePostMutation() {
return useMutation({
mutationFn: deletePostMutationFn
})
}
async function reorderPostsMutationFn(vars: ReorderPostsMutationInput): Promise<void> {
const supabase = createClient()
const results = await Promise.all(
vars.orderedPosts.map((p, index) =>
supabase.from(supabaseTablePosts).update({ grid_position: index }).eq('id', p.id)
)
)
const persistError = results.find((r) => r.error)?.error
if (persistError) throw persistError
}
function useReorderPostsMutation() {
return useMutation({
mutationFn: reorderPostsMutationFn
})
}
export {
deletePostMutationFn,
reorderPostsMutationFn,
savePostMutationFn,
useDeletePostMutation,
useReorderPostsMutation,
useSavePostMutation
}