Skip to content

Commit

Permalink
Merge pull request #527 from him2312/refactor/api-service-migration
Browse files Browse the repository at this point in the history
refactor: migrate manual api calls to api.service (fixes #526)
  • Loading branch information
ayushtom authored Mar 18, 2024
2 parents f816fa1 + 60a5525 commit 4af51c5
Show file tree
Hide file tree
Showing 15 changed files with 158 additions and 135 deletions.
54 changes: 21 additions & 33 deletions app/achievements/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import AchievementSkeleton from "@components/skeletons/achievementSkeleton";
import { useLocation } from "react-use";
import RefreshIcon from "@components/UI/iconsComponents/icons/refreshIcon";
import theme from "@styles/theme";
import { getUserAchievementByCategory, getUserAchievements, verifyUserAchievement } from "@services/apiService";

export default function Page() {
const location = useLocation();
Expand All @@ -22,38 +23,31 @@ export default function Page() {
AchievementsDocument[]
>([]);
const [loading, setLoading] = useState<boolean>(false);

const fetchAchievementsByAddress = async (address = '0') => {
const achievements = await getUserAchievements(address)
if (achievements as AchievementsDocument[]) {
setUserAchievements(achievements as AchievementsDocument[]);
}
}

useEffect(() => {
// If a call was made with an address in the first second, the call with 0 address should be cancelled
let shouldFetchWithZeroAddress = true;

// Set a 1-second timer to allow time for address loading
const timer = setTimeout(() => {
const timer = setTimeout(async () => {
// If address isn't loaded after 1 second, make the API call with the zero address
if (shouldFetchWithZeroAddress) {
fetch(`${process.env.NEXT_PUBLIC_API_LINK}/achievements/fetch?addr=0`)
.then((response) => response.json())
.then((data: AchievementsDocument[] | QueryError) => {
if (data as AchievementsDocument[])
setUserAchievements(data as AchievementsDocument[]);
});
fetchAchievementsByAddress('0')
}
}, 1000);

// If the address is loaded before the 1-second timer, make the API call with the loaded address
if (address) {
shouldFetchWithZeroAddress = false;
clearTimeout(timer);
fetch(
`${
process.env.NEXT_PUBLIC_API_LINK
}/achievements/fetch?addr=${hexToDecimal(address)}`
)
.then((response) => response.json())
.then((data: AchievementsDocument[] | QueryError) => {
if (data as AchievementsDocument[])
setUserAchievements(data as AchievementsDocument[]);
});
fetchAchievementsByAddress(hexToDecimal(address))
}
// Clear the timer when component unmounts or dependencies change to prevent memory leaks
return () => {
Expand All @@ -72,15 +66,12 @@ export default function Page() {
);
if (needsVerify.length > 0) {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_LINK}/achievements/${
achievementCategory.category_override_verified_type
}?addr=${hexToDecimal(address)}&category_id=${
achievementCategory.category_id
}`
);
const data = await getUserAchievementByCategory({
category: achievementCategory.category_override_verified_type,
address: hexToDecimal(address),
categoryId: achievementCategory.category_id
})

const data: CompletedDocument = await response.json();
if (data?.achieved && data.achieved.length > 0) {
const newUserAchievements = [...userAchievements];
data.achieved.map((task) => {
Expand All @@ -103,14 +94,11 @@ export default function Page() {
async (achievement, aIndex) => {
if (!achievement.completed) {
try {
const response = await fetch(
`${
process.env.NEXT_PUBLIC_API_LINK
}/achievements/verify_${
achievement.verify_type
}?addr=${hexToDecimal(address)}&id=${achievement.id}`
);
const data: CompletedDocument = await response.json();
const data = await verifyUserAchievement({
verifyType: achievement.verify_type,
address: hexToDecimal(address),
achievementId: achievement.id
})

if (data?.achieved) {
const newUserAchievements = [...userAchievements];
Expand Down
5 changes: 3 additions & 2 deletions app/analytics/[questId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
getQuestParticipants,
getQuestsParticipation,
getUniqueVisitorCount,
getQuestById
} from "@services/apiService";
import { getMonthName } from "@utils/stringService";
import { QuestDocument } from "../../../types/backTypes";
Expand All @@ -27,7 +28,7 @@ import { CDNImg } from "@components/cdn/image";
import { useMediaQuery } from "@mui/material";
import AnalyticsSkeleton from "@components/skeletons/analyticsSkeleton";
import { QuestDefault } from "@constants/common";
import { fetchQuestData } from "@services/questService";


type BoostQuestPageProps = {
params: {
Expand Down Expand Up @@ -69,7 +70,7 @@ export default function Page({ params }: BoostQuestPageProps) {

const fetchQuestById = useCallback(async () => {
try {
const res = await fetchQuestData(questId);
const res = await getQuestById(questId);
setQuestData(res);
} catch (error) {
console.log("Error while fetching quest data", error);
Expand Down
2 changes: 1 addition & 1 deletion app/categories/[category]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Metadata, ResolvingMetadata } from "next";
import React from "react";
import Category from "./category";
import { fetchQuestCategoryData } from "@services/questService";
import { fetchQuestCategoryData } from "@services/apiService";
import { defaultMetatags } from "@constants/metatags";

type Props = {
Expand Down
4 changes: 2 additions & 2 deletions app/quest/[questPage]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { Metadata, ResolvingMetadata } from "next";
import React from "react";
import Quest from "./quest";
import { fetchQuestData } from "@services/questService";
import { defaultMetatags } from "@constants/metatags";
import { getQuestById } from "@services/apiService";

type Props = {
params: { questPage: string };
Expand All @@ -16,7 +16,7 @@ export async function generateMetadata(
const questId = params.questPage;

try {
const data = await fetchQuestData(questId);
const data = await getQuestById(questId);

if (data?.name) {
return {
Expand Down
6 changes: 2 additions & 4 deletions app/quest/[questPage]/quest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import BannerPopup from "@components/UI/menus/bannerPopup";
import { useDomainFromAddress } from "@hooks/naming";
import NftIssuerTag from "@components/quests/nftIssuerTag";
import { QuestDefault } from "@constants/common";
import { updateUniqueVisitors } from "@services/apiService";
import { updateUniqueVisitors, getQuestById } from "@services/apiService";

type QuestPageProps = {
questId: string;
Expand Down Expand Up @@ -56,9 +56,7 @@ const Quest: FunctionComponent<QuestPageProps> = ({

// this fetches quest data
useEffect(() => {
fetch(`${process.env.NEXT_PUBLIC_API_LINK}/get_quest?id=${questId}`)
.then((response) => response.json())
.then((data: QuestDocument | QueryError) => {
getQuestById(questId).then((data: QuestDocument | QueryError) => {
if ((data as QuestDocument).name) {
if (
(data as QuestDocument).rewards_nfts &&
Expand Down
13 changes: 3 additions & 10 deletions components/lands/land.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { AchievementsDocument } from "types/backTypes";
import Link from "next/link";
import { getCurrentNetwork } from "@utils/network";
import { getNfts } from "@utils/assets";
import { fetchBuildings, getUserAchievements } from "@services/apiService";

type LandProps = {
address: string;
Expand Down Expand Up @@ -47,10 +48,7 @@ export const Land = ({
// Fetch achievements from database and add building id from highest achievement level
const getBuildingsFromAchievements = async (filteredAssets: number[]) => {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_LINK}/achievements/fetch?addr=${address}`
);
const results: AchievementsDocument[] = await response.json();
const results = await getUserAchievements(address)
if (results) {
results.forEach((result: AchievementsDocument) => {
for (let i = result.achievements.length - 1; i >= 0; i--) {
Expand All @@ -69,12 +67,7 @@ export const Land = ({
// Fetch buildings info (name, desc, img) from database
const getBuildingsInfo = async (filteredAssets: number[]) => {
try {
const response = await fetch(
`${
process.env.NEXT_PUBLIC_API_LINK
}/achievements/fetch_buildings?ids=${filteredAssets.join(",")}`
);
const results: BuildingsInfo[] = await response.json();
const results = await fetchBuildings(filteredAssets)
if (results && results.length > 0) {
setUserNft(results);
setHasNFTs(true);
Expand Down
4 changes: 2 additions & 2 deletions components/navbar/walletButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import ProfilIcon from "@components/UI/iconsComponents/icons/profilIcon";
import theme from "@styles/theme";
import Avatar from "@components/UI/avatar";
import CopyIcon from "@components/UI/iconsComponents/icons/copyIcon";
import { Wallet } from "@mui/icons-material";
import WalletIcon from "@mui/icons-material/Wallet";
import LogoutIcon from "@mui/icons-material/Logout";
import VerifiedIcon from "@components/UI/iconsComponents/icons/verifiedIcon";
import ArgentIcon from "@components/UI/iconsComponents/icons/argentIcon";
Expand Down Expand Up @@ -148,7 +148,7 @@ const WalletButton: FunctionComponent<WalletButtonProps> = ({
</button>
)}
<button onClick={handleWalletChange}>
<Wallet width="24" />
<WalletIcon width="24" />
<p>Change Wallet</p>
</button>
<button onClick={handleDisconnect}>
Expand Down
44 changes: 12 additions & 32 deletions components/quests/questDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import Timer from "./timer";
import NftImage from "./nftImage";
import { splitByNftContract } from "@utils/rewards";
import { StarknetIdJsContext } from "@context/StarknetIdJsProvider";
import { getCompletedQuests } from "@services/apiService";
import { getCompletedQuests, getEligibleRewards, getQuestParticipants, getTasksByQuestId } from "@services/apiService";

type QuestDetailsProps = {
quest: QuestDocument;
Expand Down Expand Up @@ -69,14 +69,7 @@ const QuestDetails: FunctionComponent<QuestDetailsProps> = ({
// This fetches the number of participants in the quest and up to 3 of their starknet ids
useEffect(() => {
if (questId && questId !== "0" && starknetIdNavigator) {
fetch(
`${process.env.NEXT_PUBLIC_API_LINK}/get_quest_participants?quest_id=${questId}`,
{
method: "GET",
}
)
.then((response) => response.json())
.then(async (data) => {
getQuestParticipants(questId).then(async (data) => {
setParticipants(data);
const addrs = data.firstParticipants;
const identities = addrs.map(async (addr: string) => {
Expand Down Expand Up @@ -108,29 +101,19 @@ const QuestDetails: FunctionComponent<QuestDetailsProps> = ({
const timer = setTimeout(() => {
// If address isn't loaded after 1 second, make the API call with the zero address
if (shouldFetchWithZeroAddress) {
fetch(
`${process.env.NEXT_PUBLIC_API_LINK}/get_tasks?quest_id=${questId}&addr=0`
)
.then((response) => response.json())
.then((data: UserTask[] | QueryError) => {
if ((data as UserTask[]).length) setTasks(data as UserTask[]);
});
getTasksByQuestId({questId: questId, address: '0'}).then((data) => {
if ((data as UserTask[]).length) setTasks(data as UserTask[]);
});
}
}, 1000);

// If the address is loaded before the 1-second timer, make the API call with the loaded address
if (address) {
shouldFetchWithZeroAddress = false;
clearTimeout(timer);
fetch(
`${
process.env.NEXT_PUBLIC_API_LINK
}/get_tasks?quest_id=${questId}&addr=${hexToDecimal(address)}`
)
.then((response) => response.json())
.then((data: UserTask[] | QueryError) => {
if ((data as UserTask[]).length) setTasks(data as UserTask[]);
});
getTasksByQuestId({questId: questId, address: hexToDecimal(address)}).then((data) => {
if ((data as UserTask[]).length) setTasks(data as UserTask[]);
});
}

// Clear the timer when component unmounts or dependencies change to prevent memory leaks
Expand All @@ -145,13 +128,10 @@ const QuestDetails: FunctionComponent<QuestDetailsProps> = ({
address: string | undefined
) => {
if (address && quest.rewards_endpoint) {
fetch(
`${process.env.NEXT_PUBLIC_API_LINK}/${
quest.rewards_endpoint
}?addr=${hexToDecimal(address)}`
)
.then((response) => response.json())
.then((data) => {
getEligibleRewards({
rewardEndpoint: quest.rewards_endpoint,
address: hexToDecimal(address)
}).then((data) => {
if (data.rewards) {
setEligibleRewards(splitByNftContract(data.rewards));
}
Expand Down
25 changes: 12 additions & 13 deletions components/quiz/quiz.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import EndScreen from "./endScreen";
import QuizLoading from "@components/quiz/quizLoading";
import { useAccount } from "@starknet-react/core";
import { hexToDecimal } from "@utils/feltService";
import { getQuizById } from "@services/apiService";

type QuizProps = {
setShowQuiz: (menu: ReactNode) => void;
Expand Down Expand Up @@ -65,19 +66,17 @@ const Quiz: FunctionComponent<QuizProps> = ({
useEffect(() => {
if (restart) return setRestart(false);
setLoading(true);
fetch(`${process.env.NEXT_PUBLIC_API_LINK}/get_quiz?id=${quizId}&addr=0`)
.then((res) => res.json())
.then((data) => {
const quizObj: Quiz = {
name: data.name,
description: data.desc,
questions: data.questions,
};
setAnswers([]);
setQuiz(quizObj);
setStep(-1);
setLoading(false);
});
getQuizById(quizId).then((data) => {
const quizObj: Quiz = {
name: data.name,
description: data.desc,
questions: data.questions,
};
setAnswers([]);
setQuiz(quizObj);
setStep(-1);
setLoading(false);
});
}, [quizId, restart]);

useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion context/QuestsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ReactNode, createContext, useMemo, useState } from "react";
import { QueryError, QuestDocument } from "../types/backTypes";
import { useAccount } from "@starknet-react/core";
import { hexToDecimal } from "@utils/feltService";
import { fetchQuestCategoryData } from "@services/questService";
import { fetchQuestCategoryData } from "@services/apiService";
import {
getBoostedQuests,
getCompletedBoosts,
Expand Down
9 changes: 3 additions & 6 deletions hooks/useCreationDate.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import { useEffect, useState } from "react";
import { memberSince } from "@utils/profile";
import { DeployedTime, QueryError } from "types/backTypes";
import { getDeployedTimeByAddress } from "@services/apiService";

export default function useCreationDate(identity: Identity | undefined) {
const [sinceDate, setSinceDate] = useState<string | null>(null);

useEffect(() => {
if (!identity || !identity.addr) return;
fetch(
`${process.env.NEXT_PUBLIC_API_LINK}/get_deployed_time?addr=${identity.addr}`
)
.then((res) => res.json())
.then((data: DeployedTime | QueryError) => {
getDeployedTimeByAddress(identity.addr).then((data) => {
if (data as DeployedTime) {
const sinceData = memberSince((data as DeployedTime).timestamp);
setSinceDate(sinceData);
Expand All @@ -25,4 +22,4 @@ export default function useCreationDate(identity: Identity | undefined) {
}, [identity]);

return sinceDate;
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"dependencies": {
"@emotion/react": "^11.10.0",
"@emotion/styled": "^11.10.0",
"@mui/icons-material": "^5.8.4",
"@mui/icons-material": "^5.15.12",
"@mui/material": "^5.10.1",
"@next/env": "^14.0.1",
"@nimiq/style": "^0.8.5",
Expand Down
Loading

0 comments on commit 4af51c5

Please sign in to comment.