make ranking page many speedy
All checks were successful
deploy / deploy (push) Successful in 2m11s

This commit is contained in:
Lee 2023-10-23 18:09:16 +01:00
parent dc2d502dfa
commit bab5627c51
17 changed files with 245 additions and 241 deletions

View File

@ -33,37 +33,37 @@ module.exports = withBundleAnalyzer(nextConfig);
// // Injected content via Sentry wizard below
const { withSentryConfig } = require("@sentry/nextjs");
// const { withSentryConfig } = require("@sentry/nextjs");
module.exports = withSentryConfig(
module.exports,
{
// For all available options, see:
// https://github.com/getsentry/sentry-webpack-plugin#options
// module.exports = withSentryConfig(
// module.exports,
// {
// // For all available options, see:
// // https://github.com/getsentry/sentry-webpack-plugin#options
// Suppresses source map uploading logs during build
silent: true,
org: "sentry",
project: "scoresaber-reloaded",
url: "https://sentry.fascinated.cc/",
},
{
// For all available options, see:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
// // Suppresses source map uploading logs during build
// silent: true,
// org: "sentry",
// project: "scoresaber-reloaded",
// url: "https://sentry.fascinated.cc/",
// },
// {
// // For all available options, see:
// // https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/
// Upload a larger set of source maps for prettier stack traces (increases build time)
widenClientFileUpload: false,
// // Upload a larger set of source maps for prettier stack traces (increases build time)
// widenClientFileUpload: false,
// Transpiles SDK to be compatible with IE11 (increases bundle size)
transpileClientSDK: false,
// // Transpiles SDK to be compatible with IE11 (increases bundle size)
// transpileClientSDK: false,
// Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers (increases server load)
tunnelRoute: "/monitoring",
// // Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers (increases server load)
// tunnelRoute: "/monitoring",
// Hides source maps from generated client bundles
hideSourceMaps: true,
// // Hides source maps from generated client bundles
// hideSourceMaps: true,
// Automatically tree-shake Sentry logger statements to reduce bundle size
disableLogger: true,
},
);
// // Automatically tree-shake Sentry logger statements to reduce bundle size
// disableLogger: true,
// },
// );

13
package-lock.json generated
View File

@ -25,6 +25,7 @@
"react-dom": "^18",
"react-toastify": "^9.1.3",
"sharp": "^0.32.6",
"swr": "^2.2.4",
"zustand": "^4.4.3"
},
"devDependencies": {
@ -5417,6 +5418,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/swr": {
"version": "2.2.4",
"resolved": "https://registry.npmjs.org/swr/-/swr-2.2.4.tgz",
"integrity": "sha512-njiZ/4RiIhoOlAaLYDqwz5qH/KZXVilRLvomrx83HjzCWTfa+InyfAjv05PSFxnmLzZkNO9ZfvgoqzAaEI4sGQ==",
"dependencies": {
"client-only": "^0.0.1",
"use-sync-external-store": "^1.2.0"
},
"peerDependencies": {
"react": "^16.11.0 || ^17.0.0 || ^18.0.0"
}
},
"node_modules/tailwindcss": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.3.tgz",

View File

@ -26,6 +26,7 @@
"react-dom": "^18",
"react-toastify": "^9.1.3",
"sharp": "^0.32.6",
"swr": "^2.2.4",
"zustand": "^4.4.3"
},
"devDependencies": {

View File

@ -1,4 +1,4 @@
import PlayerPage from "@/components/player/PlayerPage";
import PlayerPage from "@/components/player/Player";
import { ssrSettings } from "@/ssrSettings";
import { formatNumber } from "@/utils/number";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";

View File

@ -0,0 +1,44 @@
import Card from "@/components/Card";
import Container from "@/components/Container";
import Error from "@/components/Error";
import GlobalRanking from "@/components/player/GlobalRanking";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
type RankingGlobalProps = {
params: { page: string; country: string };
};
// Get data from API (server-sided)
async function getData(page: number, country: string) {
const pageData = await ScoreSaberAPI.fetchTopPlayers(page);
if (!pageData) {
return undefined;
}
return pageData;
}
export default async function RankingGlobal({
params: { page, country },
}: RankingGlobalProps) {
const pageData = await getData(Number(page), country);
return (
<main>
<Container>
<Card className="mt-2">
{pageData == undefined && (
<Error errorMessage="Failed to load players. Is the page valid?" />
)}
{pageData && (
<GlobalRanking
page={Number(page)}
players={pageData.players}
totalPages={pageData.pageInfo.totalPages}
country={country}
/>
)}
</Card>
</Container>
</main>
);
}

View File

@ -1,14 +0,0 @@
import GlobalRanking from "@/components/player/GlobalRanking";
import { getPageFromSearchQuery } from "@/utils/utils";
import { headers } from "next/headers";
type RankingCountryProps = {
params: { country: string };
};
export default function RankingCountry({ params }: RankingCountryProps) {
const page = getPageFromSearchQuery(headers());
const country = params.country;
return <GlobalRanking page={page} country={country} />;
}

View File

@ -0,0 +1,43 @@
import Card from "@/components/Card";
import Container from "@/components/Container";
import Error from "@/components/Error";
import GlobalRanking from "@/components/player/GlobalRanking";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
type RankingGlobalProps = {
params: { page: string };
};
// Get data from API (server-sided)
async function getData(page: number) {
const pageData = await ScoreSaberAPI.fetchTopPlayers(page);
if (!pageData || pageData.players.length == 0) {
return undefined;
}
return pageData;
}
export default async function RankingGlobal({
params: { page },
}: RankingGlobalProps) {
const pageData = await getData(Number(page));
return (
<main>
<Container>
<Card className="mt-2">
{pageData == undefined && (
<Error errorMessage="Failed to load players. Is the page valid?" />
)}
{pageData && (
<GlobalRanking
page={Number(page)}
players={pageData.players}
totalPages={pageData.pageInfo.totalPages}
/>
)}
</Card>
</Container>
</main>
);
}

View File

@ -1,9 +0,0 @@
import GlobalRanking from "@/components/player/GlobalRanking";
import { getPageFromSearchQuery } from "@/utils/utils";
import { headers } from "next/headers";
export default function RankingGlobal() {
const page = getPageFromSearchQuery(headers());
return <GlobalRanking page={page} />;
}

View File

@ -1,186 +1,100 @@
"use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
import { normalizedRegionName } from "@/utils/utils";
import dynamic from "next/dynamic";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import Card from "../Card";
import Container from "../Container";
import Pagination from "../Pagination";
import Spinner from "../Spinner";
import PlayerRanking from "./PlayerRanking";
import PlayerRankingMobile from "./PlayerRankingMobile";
const ReactCountryFlag = dynamic(() => import("react-country-flag"));
const Error = dynamic(() => import("@/components/Error"));
type PageInfo = {
loading: boolean;
page: number;
totalPages: number;
players: ScoresaberPlayer[];
};
type GlobalRankingProps = {
page: number;
totalPages: number;
country?: string;
players: ScoresaberPlayer[];
};
export default function GlobalRanking({ page, country }: GlobalRankingProps) {
export default function GlobalRanking({
page,
totalPages,
country,
players,
}: GlobalRankingProps) {
const router = useRouter();
const [error, setError] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [pageInfo, setPageInfo] = useState<PageInfo>({
loading: true,
page: page,
totalPages: 1,
players: [],
});
const updatePage = useCallback(
(page: any) => {
console.log("Switching page to", page);
ScoreSaberAPI.fetchTopPlayers(page, country).then((response) => {
if (!response) {
setError(true);
setErrorMessage("No players found");
setPageInfo({ ...pageInfo, loading: false });
return;
}
setPageInfo({
...pageInfo,
players: response.players,
totalPages: response.pageInfo.totalPages,
loading: false,
page: page,
});
const urlBase = country
? `/ranking/country/${country}`
: "/ranking/global";
if (page > 1) {
router.push(`${urlBase}?page=${page}`, {
scroll: false,
});
} else {
router.push(`${urlBase}`, {
scroll: false,
});
}
});
},
[country, pageInfo, router],
);
useEffect(() => {
if (!pageInfo.loading || error) return;
updatePage(pageInfo.page);
}, [error, country, updatePage, pageInfo.page, pageInfo.loading]);
if (pageInfo.loading || error) {
return (
<main>
<Container>
<Card className="mt-2">
<div className="p-3 text-center">
<div role="status">
<div className="flex flex-col items-center justify-center gap-2">
{error && <Error errorMessage={errorMessage} />}
{!error && <Spinner />}
</div>
</div>
</div>
</Card>
</Container>
</main>
);
}
const players = pageInfo.players;
return (
<main>
<Container>
<Card className="mt-2">
{pageInfo.loading ? (
<div className="flex justify-center">
<Spinner />
</div>
) : (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 rounded-md bg-gray-700 p-2">
{country && (
<ReactCountryFlag
countryCode={country}
svg
className="!h-8 !w-8"
/>
)}
<p>
You are viewing{" "}
{country
? "scores from " + normalizedRegionName(country)
: "Global scores"}
</p>
</div>
<table className="hidden w-full table-auto border-spacing-2 border-none text-left md:table">
<thead>
<tr>
<th className="px-4 py-2">Rank</th>
<th className="px-4 py-2">Profile</th>
<th className="px-4 py-2">Performance Points</th>
<th className="px-4 py-2">Total Plays</th>
<th className="px-4 py-2">Total Ranked Plays</th>
<th className="px-4 py-2">Avg Ranked Accuracy</th>
</tr>
</thead>
<tbody className="border-none">
{players.map((player) => (
<tr key={player.rank} className="border-b border-gray-700">
<PlayerRanking
showCountryFlag={country ? false : true}
player={player}
/>
</tr>
))}
</tbody>
</table>
<div className="flex flex-col gap-2 md:hidden">
{players.map((player) => (
<div
key={player.rank}
className="flex flex-col gap-2 rounded-md bg-gray-700 hover:bg-gray-600"
>
<Link href={`/player/${player.id}`}>
<PlayerRankingMobile player={player} />
</Link>
</div>
))}
</div>
{/* Pagination */}
<div className="flex w-full flex-row justify-center rounded-md bg-gray-800 md:flex-col">
<div className="p-3">
<Pagination
currentPage={pageInfo.page}
totalPages={pageInfo.totalPages}
onPageChange={(page) => {
updatePage(page);
}}
/>
</div>
</div>
</div>
<>
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 rounded-md bg-gray-700 p-2">
{country && (
<ReactCountryFlag countryCode={country} svg className="!h-8 !w-8" />
)}
</Card>
</Container>
</main>
<p>
You are viewing{" "}
{country
? "scores from " + normalizedRegionName(country)
: "Global scores"}
</p>
</div>
<table className="hidden w-full table-auto border-spacing-2 border-none text-left md:table">
<thead>
<tr>
<th className="px-4 py-2">Rank</th>
<th className="px-4 py-2">Profile</th>
<th className="px-4 py-2">Performance Points</th>
<th className="px-4 py-2">Total Plays</th>
<th className="px-4 py-2">Total Ranked Plays</th>
<th className="px-4 py-2">Avg Ranked Accuracy</th>
</tr>
</thead>
<tbody className="border-none">
{players.map((player) => (
<tr key={player.rank} className="border-b border-gray-700">
<PlayerRanking
showCountryFlag={country ? false : true}
player={player}
/>
</tr>
))}
</tbody>
</table>
<div className="flex flex-col gap-2 md:hidden">
{players.map((player) => (
<div
key={player.rank}
className="flex flex-col gap-2 rounded-md bg-gray-700 hover:bg-gray-600"
>
<Link href={`/player/${player.id}`}>
<PlayerRankingMobile player={player} />
</Link>
</div>
))}
</div>
{/* Pagination */}
<div className="flex w-full flex-row justify-center rounded-md bg-gray-800 md:flex-col">
<div className="p-3">
<Pagination
currentPage={page}
totalPages={totalPages}
onPageChange={(page) => {
const urlBase = country
? `/ranking/country/${country}`
: `/ranking/global`;
router.push(`${urlBase}/${page}`, {
scroll: false,
});
}}
/>
</div>
</div>
</div>
</>
);
}

View File

@ -6,7 +6,6 @@ import {
calcPpBoundary,
getAveragePp,
getHighestPpPlay,
getTotalScores,
} from "@/utils/scoresaber/scores";
import {
GlobeAsiaAustraliaIcon,
@ -167,9 +166,7 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
<a
className="flex transform-gpu items-center gap-1 transition-all hover:text-blue-500"
href={`/ranking/global/?page=${Math.round(
playerData.rank / 50,
)}`}
href={`/ranking/global/${Math.ceil(playerData.rank / 50)}`}
>
<p>#{formatNumber(playerData.rank)}</p>
</a>
@ -179,7 +176,7 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
<div className="text-gray-300">
<a
className="flex transform-gpu items-center gap-1 transition-all hover:text-blue-500"
href={`/ranking/country/${playerData.country}?page=${Math.round(
href={`/ranking/country/${playerData.country}/${Math.ceil(
playerData.countryRank / 50,
)}`}
>

View File

@ -1,3 +1,5 @@
"use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { useSettingsStore } from "@/store/settingsStore";
import { formatNumber } from "@/utils/number";

View File

@ -1,3 +1,5 @@
"use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { useSettingsStore } from "@/store/settingsStore";
import { formatNumber } from "@/utils/number";
@ -22,7 +24,7 @@ export default function PlayerRankingMobile({
return (
<div>
<div className="m-3 flex flex-col gap-2">
<p className="flex items-center gap-2">
<div className="flex items-center gap-2">
<p>#{formatNumber(player.rank)}</p>
<Avatar url={player.profilePicture} label="Avatar" size={24} />
{showCountryFlag && (
@ -41,7 +43,7 @@ export default function PlayerRankingMobile({
>
{player.name}
</p>
</p>
</div>
<div className="flex flex-wrap justify-center gap-2">
<Label
title="PP"

View File

@ -2,11 +2,17 @@ import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// todo: make this redirect to the users profile if they have a profile selected
if (request.nextUrl.pathname == "/") {
if (pathname == "/") {
return NextResponse.redirect(new URL("/search", request.url));
}
if (pathname == "/ranking/global") {
return NextResponse.redirect(new URL("/ranking/global/1", request.url));
}
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-url", request.url);
return NextResponse.next({

View File

@ -23,7 +23,11 @@ export class FetchQueue {
);
}
const response = await fetch(url);
const response = await fetch(url, {
next: {
revalidate: 3600, // Keep the data for 1 hour, then fetch new data
},
});
if (response.status === 429) {
const hasRetryAfter = response.headers.has("retry-after");
let retryAfter =

View File

@ -5,17 +5,18 @@ import { FetchQueue } from "../fetchWithQueue";
import { formatString } from "../string";
// Create a fetch instance with a cache
const fetchQueue = new FetchQueue();
export const ScoresaberFetchQueue = new FetchQueue();
// Api endpoints
const API_URL = ssrSettings.proxy + "/https://scoresaber.com/api";
const SEARCH_PLAYER_URL =
API_URL + "/players?search={}&page=1&withMetadata=false";
const PLAYER_SCORES =
API_URL + "/player/{}/scores?limit={}&sort={}&page={}&withMetadata=true";
const GET_PLAYER_DATA_FULL = API_URL + "/player/{}/full";
const GET_PLAYERS_URL = API_URL + "/players?page={}";
const GET_PLAYERS_BY_COUNTRY_URL = API_URL + "/players?page={}&countries={}";
const SS_API_URL = ssrSettings.proxy + "/https://scoresaber.com/api";
export const SS_SEARCH_PLAYER_URL =
SS_API_URL + "/players?search={}&page=1&withMetadata=false";
export const SS_PLAYER_SCORES =
SS_API_URL + "/player/{}/scores?limit={}&sort={}&page={}&withMetadata=true";
export const SS_GET_PLAYER_DATA_FULL = SS_API_URL + "/player/{}/full";
export const SS_GET_PLAYERS_URL = SS_API_URL + "/players?page={}";
export const SS_GET_PLAYERS_BY_COUNTRY_URL =
SS_API_URL + "/players?page={}&countries={}";
const SearchType = {
RECENT: "recent",
@ -31,8 +32,8 @@ const SearchType = {
async function searchByName(
name: string,
): Promise<ScoresaberPlayer[] | undefined> {
const response = await fetchQueue.fetch(
formatString(SEARCH_PLAYER_URL, true, name),
const response = await ScoresaberFetchQueue.fetch(
formatString(SS_SEARCH_PLAYER_URL, true, name),
);
const json = await response.json();
@ -53,8 +54,8 @@ async function searchByName(
async function fetchPlayerData(
playerId: string,
): Promise<ScoresaberPlayer | undefined | null> {
const response = await fetchQueue.fetch(
formatString(GET_PLAYER_DATA_FULL, true, playerId),
const response = await ScoresaberFetchQueue.fetch(
formatString(SS_GET_PLAYER_DATA_FULL, true, playerId),
);
const json = await response.json();
@ -94,8 +95,8 @@ async function fetchScores(
if (limit > 100) {
throw new Error("Limit cannot be greater than 100");
}
const response = await fetchQueue.fetch(
formatString(PLAYER_SCORES, true, playerId, limit, searchType, page),
const response = await ScoresaberFetchQueue.fetch(
formatString(SS_PLAYER_SCORES, true, playerId, limit, searchType, page),
);
const json = await response.json();
@ -177,9 +178,9 @@ async function fetchTopPlayers(
| undefined
> {
const url = country
? formatString(GET_PLAYERS_BY_COUNTRY_URL, true, page, country)
: formatString(GET_PLAYERS_URL, true, page);
const response = await fetchQueue.fetch(url);
? formatString(SS_GET_PLAYERS_BY_COUNTRY_URL, true, page, country)
: formatString(SS_GET_PLAYERS_URL, true, page);
const response = await ScoresaberFetchQueue.fetch(url);
const json = await response.json();
// Check if there was an error fetching the user data

View File

@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es5",
"target": "ES2016",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,