diff --git a/web/src/components/post-card.tsx b/web/src/components/post-card.tsx index c230b2f..5ae9179 100644 --- a/web/src/components/post-card.tsx +++ b/web/src/components/post-card.tsx @@ -3,6 +3,8 @@ import { CountCommentsRequest, CountCommentsResponse, ENDPOINT_CONFIGS, + GetUserRequest, + GetUserResponse, Post, } from '@codersquare/shared'; import { useQuery } from '@tanstack/react-query'; @@ -12,36 +14,64 @@ import { Link } from 'react-router-dom'; import { callEndpoint } from '../fetch'; export const PostCard: React.FC = post => { - const { method, url } = ENDPOINT_CONFIGS.countComments; - const { - data: commentCount, - isLoading, - error, - } = useQuery([`countComments${post.id}`], () => - callEndpoint( - url.replace(':postId', post.id), - method, - { postId: post.id } - ) - ); + const { id, url: postUrl, title, userId } = post; + const { user, error, isLoading } = useGetUser(userId); + const { countCommentsRes } = useCountComments(id); - const count = isLoading ? '...' : error ? 'unknown' : commentCount?.count ?? '0'; + const urlWithProtocol = postUrl.startsWith('http') ? postUrl : 'http://' + postUrl; + const userName = isLoading || !user ? '...' : error ? '' : user.userName; + const commentsCount = countCommentsRes?.count ?? 0; return ( - {post.title} + {title} - ({post.url}) + ({getUrlDomain(urlWithProtocol)}) + + {userName} ); }; + +const getUrlDomain = (url: string): string => { + try { + const short = new URL(url).host; + return short.startsWith('www.') ? short.substring(4) : short; + } catch { + return url; + } +}; + +const useGetUser = (userId: string) => { + const { method, url } = ENDPOINT_CONFIGS.getUser; + const { + data: user, + error, + isLoading, + } = useQuery([`getuser${userId}`], () => + callEndpoint(url.replace(':id', userId), method, {}) + ); + return { user, error, isLoading }; +}; + +const useCountComments = (postId: string) => { + const { method, url } = ENDPOINT_CONFIGS.countComments; + const { data: countCommentsRes } = useQuery([`countComments${postId}`], () => + callEndpoint( + url.replace(':postId', postId), + method, + { postId } + ) + ); + return { countCommentsRes }; +};