mirror of
https://github.com/r-freeman/portfolio.git
synced 2025-04-12 01:04:30 +00:00
All checks were successful
Build And Publish / BuildAndPublish (push) Successful in 3m13s
51 lines
1.7 KiB
TypeScript
51 lines
1.7 KiB
TypeScript
import {createClient} from '@/lib/supabase/client'
|
|
import {QueryData} from '@supabase/supabase-js'
|
|
|
|
export async function getComments(slug: string) {
|
|
try {
|
|
const supabase = await createClient()
|
|
const commentsQuery = supabase
|
|
.from('comments')
|
|
.select(`
|
|
id,
|
|
content,
|
|
published,
|
|
created_at,
|
|
parent_id,
|
|
user:users!inner(id, name, image),
|
|
article:articles!inner(id, title, slug)
|
|
`)
|
|
.eq('article.slug', slug)
|
|
.eq('published', true)
|
|
.order('created_at', {ascending: false})
|
|
|
|
type Comments = QueryData<typeof commentsQuery>
|
|
|
|
const {data: comments, error} = await commentsQuery
|
|
|
|
const commentMap = comments?.reduce<{ [key: number]: Comment }>((acc, comment) => {
|
|
// @ts-ignore
|
|
acc[comment.id] = {...comment, replies: []}
|
|
return acc
|
|
}, {});
|
|
|
|
return comments?.reduce<Comment[]>((nested, comment) => {
|
|
if (typeof commentMap !== 'undefined') {
|
|
if (comment.parent_id !== null) {
|
|
const parent = commentMap[comment.parent_id];
|
|
if (parent) {
|
|
// @ts-ignore
|
|
parent.replies?.push(commentMap[comment.id])
|
|
// @ts-ignore
|
|
parent.replies?.sort((a, b) => a.id - b.id)
|
|
}
|
|
} else {
|
|
nested.push(commentMap[comment.id]);
|
|
}
|
|
}
|
|
return nested;
|
|
}, [])
|
|
} catch (error) {
|
|
console.error(error)
|
|
}
|
|
} |