Restructure codebase to use src directory

This commit is contained in:
Aaron William Po
2023-04-11 23:32:06 -04:00
parent 90f2cc2c0c
commit 08422fe24e
141 changed files with 6 additions and 4 deletions

View File

@@ -0,0 +1,70 @@
import BeerCommentQueryResult from '@/services/BeerComment/schema/BeerCommentQueryResult';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod';
import useSWRInfinite from 'swr/infinite';
interface UseBeerPostCommentsProps {
pageNum: number;
id: string;
pageSize: number;
}
/**
* A custom React hook that fetches comments for a specific beer post.
*
* @param props - The props object.
* @param props.pageNum - The page number of the comments to fetch.
* @param props.id - The ID of the beer post to fetch comments for.
* @param props.pageSize - The number of comments to fetch per page.
* @returns An object containing the fetched comments, the total number of comment pages,
* a boolean indicating if the request is currently loading, and a function to mutate
* the data.
*/
const useBeerPostComments = ({ id, pageSize }: UseBeerPostCommentsProps) => {
const fetcher = async (url: string) => {
const response = await fetch(url);
const json = await response.json();
const count = response.headers.get('X-Total-Count');
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error(parsed.error.message);
}
const parsedPayload = z.array(BeerCommentQueryResult).safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error(parsedPayload.error.message);
}
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
return { comments: parsedPayload.data, pageCount };
};
const { data, error, isLoading, mutate, size, setSize } = useSWRInfinite(
(index) => `/api/beers/${id}/comments?page_num=${index + 1}&page_size=${pageSize}`,
fetcher,
{ parallel: true },
);
const comments = data?.flatMap((d) => d.comments) ?? [];
const pageCount = data?.[0].pageCount ?? 0;
const isLoadingMore =
isLoading || (size > 0 && data && typeof data[size - 1] === 'undefined');
const isAtEnd = !(size < data?.[0].pageCount!);
return {
comments,
isLoading,
error: error as undefined,
mutate,
size,
setSize,
isLoadingMore,
isAtEnd,
pageCount,
};
};
export default useBeerPostComments;

View File

@@ -0,0 +1,37 @@
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import useSWR from 'swr';
import { z } from 'zod';
/**
* A custom React hook that searches for beer posts that match a given query string.
*
* @param query The search query string to match beer posts against.
* @returns An object containing an array of search results matching the query, an error
* object if an error occurred during the search, and a boolean indicating if the
* request is currently loading.
*/
const useBeerPostSearch = (query: string | undefined) => {
const { data, isLoading, error } = useSWR(
`/api/beers/search?search=${query}`,
async (url) => {
if (!query) return [];
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const json = await response.json();
const result = z.array(beerPostQueryResult).parse(json);
return result;
},
);
return {
searchResults: data,
searchError: error as Error | undefined,
isLoading,
};
};
export default useBeerPostSearch;

View File

@@ -0,0 +1,56 @@
import UserContext from '@/contexts/userContext';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { useContext } from 'react';
import useSWR from 'swr';
import { z } from 'zod';
/**
* A custom React hook that checks if the current user has liked a beer post by fetching
* data from the server.
*
* @param beerPostId The ID of the beer post to check for likes.
* @returns An object containing a boolean indicating if the user has liked the beer post,
* an error object if an error occurred during the request, and a boolean indicating if
* the request is currently loading.
* @throws When the user is not logged in, the server returns an error status code, or if
* the response data fails to validate against the expected schema.
*/
const useCheckIfUserLikesBeerPost = (beerPostId: string) => {
const { user } = useContext(UserContext);
const { data, error, isLoading, mutate } = useSWR(
`/api/beers/${beerPostId}/like/is-liked`,
async () => {
if (!user) {
throw new Error('User is not logged in.');
}
const response = await fetch(`/api/beers/${beerPostId}/like/is-liked`);
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('Invalid API response.');
}
const { payload } = parsed.data;
const parsedPayload = z.object({ isLiked: z.boolean() }).safeParse(payload);
if (!parsedPayload.success) {
throw new Error('Invalid API response.');
}
const { isLiked } = parsedPayload.data;
return isLiked;
},
);
return {
isLiked: data,
error: error as unknown,
isLoading,
mutate,
};
};
export default useCheckIfUserLikesBeerPost;

View File

@@ -0,0 +1,48 @@
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { z } from 'zod';
import useSWR from 'swr';
/**
* Custom hook to fetch the like count for a beer post from the server.
*
* @param beerPostId - The ID of the beer post to fetch the like count for.
* @returns An object with the current like count, as well as metadata about the current
* state of the request.
*/
const useGetLikeCount = (beerPostId: string) => {
const { error, mutate, data, isLoading } = useSWR(
`/api/beers/${beerPostId}/like`,
async (url) => {
const response = await fetch(url);
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('Failed to parse API response');
}
const parsedPayload = z
.object({
likeCount: z.number(),
})
.safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error('Failed to parse API response payload');
}
return parsedPayload.data.likeCount;
},
);
return {
error: error as unknown,
isLoading,
mutate,
likeCount: data as number | undefined,
};
};
export default useGetLikeCount;

View File

@@ -0,0 +1,19 @@
import { useState, useEffect } from 'react';
const useMediaQuery = (query: string) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => setMatches(media.matches);
window.addEventListener('resize', listener);
return () => window.removeEventListener('resize', listener);
}, [matches, query]);
return matches;
};
export default useMediaQuery;

View File

@@ -0,0 +1,22 @@
import UserContext from '@/contexts/userContext';
import { useRouter } from 'next/router';
import { useContext } from 'react';
/**
* Custom React hook that redirects the user to the home page if they are logged in. This
* hook is used to prevent logged in users from accessing the login and signup pages. Must
* be used under the UserContext provider.
*
* @returns {void}
*/
const useRedirectWhenLoggedIn = (): void => {
const { user } = useContext(UserContext);
const router = useRouter();
if (!user) {
return;
}
router.push('/');
};
export default useRedirectWhenLoggedIn;

View File

@@ -0,0 +1,20 @@
import formatDistanceStrict from 'date-fns/formatDistanceStrict';
import { useState, useEffect } from 'react';
/**
* Returns the time distance between the provided date and the current time, using the
* `date-fns` `formatDistanceStrict` function. This hook ensures that the same result is
* calculated on both the server and client, preventing hydration errors.
*
* @param createdAt The date to calculate the time distance from.
* @returns The time distance between the provided date and the current time.
*/
const useTimeDistance = (createdAt: Date) => {
const [timeDistance, setTimeDistance] = useState('');
useEffect(() => {
setTimeDistance(formatDistanceStrict(createdAt, new Date()));
}, [createdAt]);
return timeDistance;
};
export default useTimeDistance;

50
src/hooks/useUser.ts Normal file
View File

@@ -0,0 +1,50 @@
import GetUserSchema from '@/services/User/schema/GetUserSchema';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import useSWR from 'swr';
/**
* A custom React hook that fetches the current user's data from the server.
*
* @returns An object containing the current user's data, a boolean indicating if the
* request is currently loading, and an error object if an error occurred during the
* request.
* @throws When the user is not logged in, the server returns an error status code, or if
* the response data fails to validate against the expected schema.
*/
const useUser = () => {
const {
data: user,
error,
isLoading,
mutate,
} = useSWR('/api/users/current', async (url) => {
if (!document.cookie.includes('token')) {
throw new Error('No token cookie found');
}
const response = await fetch(url);
if (!response.ok) {
document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
throw new Error(response.statusText);
}
const json = await response.json();
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error(parsed.error.message);
}
const parsedPayload = GetUserSchema.safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error(parsedPayload.error.message);
}
return parsedPayload.data;
});
return { user, isLoading, error: error as unknown, mutate };
};
export default useUser;