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

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

13
package-lock.json generated

@ -25,6 +25,7 @@
"react-dom": "^18", "react-dom": "^18",
"react-toastify": "^9.1.3", "react-toastify": "^9.1.3",
"sharp": "^0.32.6", "sharp": "^0.32.6",
"swr": "^2.2.4",
"zustand": "^4.4.3" "zustand": "^4.4.3"
}, },
"devDependencies": { "devDependencies": {
@ -5417,6 +5418,18 @@
"url": "https://github.com/sponsors/ljharb" "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": { "node_modules/tailwindcss": {
"version": "3.3.3", "version": "3.3.3",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.3.tgz", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.3.3.tgz",

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

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

@ -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>
);
}

@ -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} />;
}

@ -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>
);
}

@ -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} />;
}

@ -1,125 +1,37 @@
"use client"; "use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player"; import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
import { normalizedRegionName } from "@/utils/utils"; import { normalizedRegionName } from "@/utils/utils";
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import Card from "../Card";
import Container from "../Container";
import Pagination from "../Pagination"; import Pagination from "../Pagination";
import Spinner from "../Spinner";
import PlayerRanking from "./PlayerRanking"; import PlayerRanking from "./PlayerRanking";
import PlayerRankingMobile from "./PlayerRankingMobile"; import PlayerRankingMobile from "./PlayerRankingMobile";
const ReactCountryFlag = dynamic(() => import("react-country-flag")); 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 = { type GlobalRankingProps = {
page: number; page: number;
totalPages: number;
country?: string; country?: string;
players: ScoresaberPlayer[];
}; };
export default function GlobalRanking({ page, country }: GlobalRankingProps) { export default function GlobalRanking({
page,
totalPages,
country,
players,
}: GlobalRankingProps) {
const router = useRouter(); 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 ( 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 flex-col gap-2">
<div className="flex items-center gap-2 rounded-md bg-gray-700 p-2"> <div className="flex items-center gap-2 rounded-md bg-gray-700 p-2">
{country && ( {country && (
<ReactCountryFlag <ReactCountryFlag countryCode={country} svg className="!h-8 !w-8" />
countryCode={country}
svg
className="!h-8 !w-8"
/>
)} )}
<p> <p>
You are viewing{" "} You are viewing{" "}
@ -169,18 +81,20 @@ export default function GlobalRanking({ page, country }: GlobalRankingProps) {
<div className="flex w-full flex-row justify-center rounded-md bg-gray-800 md:flex-col"> <div className="flex w-full flex-row justify-center rounded-md bg-gray-800 md:flex-col">
<div className="p-3"> <div className="p-3">
<Pagination <Pagination
currentPage={pageInfo.page} currentPage={page}
totalPages={pageInfo.totalPages} totalPages={totalPages}
onPageChange={(page) => { onPageChange={(page) => {
updatePage(page); const urlBase = country
? `/ranking/country/${country}`
: `/ranking/global`;
router.push(`${urlBase}/${page}`, {
scroll: false,
});
}} }}
/> />
</div> </div>
</div> </div>
</div> </div>
)} </>
</Card>
</Container>
</main>
); );
} }

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

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

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

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

@ -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) { if (response.status === 429) {
const hasRetryAfter = response.headers.has("retry-after"); const hasRetryAfter = response.headers.has("retry-after");
let retryAfter = let retryAfter =

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

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