Skip to content

Commit

Permalink
shorten url and display username
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasser Elsayed committed Sep 1, 2022
1 parent a26a762 commit 0b0fcb2
Showing 1 changed file with 46 additions and 16 deletions.
62 changes: 46 additions & 16 deletions web/src/components/post-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {
CountCommentsRequest,
CountCommentsResponse,
ENDPOINT_CONFIGS,
GetUserRequest,
GetUserResponse,
Post,
} from '@codersquare/shared';
import { useQuery } from '@tanstack/react-query';
Expand All @@ -12,36 +14,64 @@ import { Link } from 'react-router-dom';
import { callEndpoint } from '../fetch';

export const PostCard: React.FC<Post> = post => {
const { method, url } = ENDPOINT_CONFIGS.countComments;
const {
data: commentCount,
isLoading,
error,
} = useQuery([`countComments${post.id}`], () =>
callEndpoint<CountCommentsRequest, CountCommentsResponse>(
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 ? '<unknown>' : user.userName;
const commentsCount = countCommentsRes?.count ?? 0;

return (
<Box>
<Flex gap={2}>
<Text fontSize="md" fontWeight="bold" color="gray.600">
{post.title}
{title}
</Text>
<Text fontWeight="bold" color="gray.300">
({post.url})
({getUrlDomain(urlWithProtocol)})
</Text>
<Link to={`/p/${post.id}`}>
<Button variant="outline" size="sm" color="gray.400">
{count} comments
{commentsCount} comments
</Button>
</Link>
</Flex>

<Text>{userName}</Text>
</Box>
);
};

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<GetUserRequest, GetUserResponse>(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<CountCommentsRequest, CountCommentsResponse>(
url.replace(':postId', postId),
method,
{ postId }
)
);
return { countCommentsRes };
};

0 comments on commit 0b0fcb2

Please sign in to comment.