Skip to content

Commit

Permalink
Fix the maps and add new API endpoint for desktop app (#520)
Browse files Browse the repository at this point in the history
* Fix the maps and add new API endpoint for desktop app

* Fix the tests
  • Loading branch information
petrvecera authored Jul 23, 2024
1 parent 0832e87 commit 3ac1796
Show file tree
Hide file tree
Showing 9 changed files with 70 additions and 38 deletions.
2 changes: 1 addition & 1 deletion __tests__/pages/api/onlineSteamPlayers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe("onlineSteamApiPlayersHandler", () => {
test("should return 200 status code and player count and timestamp in response", async () => {
await handler(req, res);

expect(res.setHeader).toHaveBeenCalledWith("Cache-Control", "public");
expect(res.setHeader).toHaveBeenCalledWith("Cache-Control", "public, max-age=300");
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith({
playerCount: 5,
Expand Down
1 change: 1 addition & 0 deletions __tests__/src/apis/coh3stats-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,7 @@ describe("coh3stats-api", () => {
const response = await getStatsData(123, "now", "gameStats", "cache-key-4");
expect(global.fetch).toBeCalledWith(
`https://cache.coh3stats.com/getAnalysisStatsHttp?startDate=123&endDate=now&type=gameStats&v=${GET_ANALYSIS_STATS}&ock=cache-key-4`,
{ headers: undefined },
);

expect(response).toEqual(fakeStatsData);
Expand Down
10 changes: 10 additions & 0 deletions __tests__/src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ describe("getIconsPathOnCDN", () => {
expect(result).toBe(`${config.CDN_ASSETS_HOSTING}/export/my_icon.webp`);
});

test("should change to png in the export folder", () => {
const result = getIconsPathOnCDN("my_icon.png", "export");
expect(result).toBe(`${config.CDN_ASSETS_HOSTING}/export/my_icon.webp`);
});

test("should return the correctly formed URL for the export_flatten folder", () => {
const result = getIconsPathOnCDN("/path/to/my_icon", "export_flatten");
expect(result).toBe(`${config.CDN_ASSETS_HOSTING}/export_flatten/my_icon.webp`);
Expand All @@ -38,6 +43,11 @@ describe("getIconsPathOnCDN", () => {
const result = getIconsPathOnCDN("/path/to/my_icon.webp", "export_flatten");
expect(result).toBe(`${config.CDN_ASSETS_HOSTING}/export_flatten/my_icon.webp`);
});

test("correctly gets path for maps", () => {
const result = getIconsPathOnCDN("/map_icon/map_icon", "maps");
expect(result).toBe(`${config.CDN_ASSETS_HOSTING}/maps/map_icon/map_icon.webp`);
});
});

describe("internalSlash", () => {
Expand Down
4 changes: 2 additions & 2 deletions components/matches-table/render-map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { isOfficialMap, maps } from "../../src/coh3/coh3-data";
import { Text, Tooltip } from "@mantine/core";
import React from "react";
import ImageWithModal from "../image-with-modal";
import { getMapsPathOnCDN } from "../../src/utils";
import { getIconsPathOnCDN } from "../../src/utils";

const RenderMap = ({ mapName, renderTitle }: { mapName: string; renderTitle?: boolean }) => {
renderTitle = renderTitle ?? true;
Expand All @@ -27,7 +27,7 @@ const RenderMap = ({ mapName, renderTitle }: { mapName: string; renderTitle?: bo
height={60}
width={60}
alt={mapName}
src={getMapsPathOnCDN(maps[mapName]?.url)}
src={getIconsPathOnCDN(maps[mapName]?.url, "maps")}
title={maps[mapName].name}
/>
</div>
Expand Down
37 changes: 37 additions & 0 deletions pages/api/getLatestPatchMapStats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { logger } from "../../src/logger";
import { NextApiRequest, NextApiResponse } from "next";
import config from "../../config";
import { generateExpireTimeStamps, getGMTTimeStamp } from "../../src/utils";
import { getStatsData } from "../../src/apis/coh3stats-api";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const statsPatchSelector = config.statsPatchSelector;
const fromTimeStamp = getGMTTimeStamp(new Date(statsPatchSelector[config.latestPatch].from));

const data = await getStatsData(
fromTimeStamp,
"now",
"mapStats",
"https://coh3stats.com",
["all"],
{
Origin: "https://coh3stats.com",
},
);

const response = {
latestPatchInfo: statsPatchSelector[config.latestPatch],
mapStats: data,
};

res
.setHeader("Cache-Control", "public")
.setHeader("Expires", generateExpireTimeStamps(7))
.status(200)
.json(response);
} catch (e) {
logger.error(e);
res.status(500).json({});
}
}
2 changes: 1 addition & 1 deletion pages/api/onlineSteamPlayers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const { response } = await fetchResponse.json();

res
.setHeader("Cache-Control", "public")
.setHeader("Cache-Control", "public, max-age=300")
.status(200)
.json({ playerCount: response.player_count, timeStampMs: new Date().valueOf() });
} catch (e) {
Expand Down
7 changes: 6 additions & 1 deletion screens/stats/maps/inner-map-stats-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ImageWithModal from "../../../components/image-with-modal";
import { isOfficialMap, maps } from "../../../src/coh3/coh3-data";
import dynamic from "next/dynamic";
import MapChartCard from "./map-chart-card";
import { getIconsPathOnCDN } from "../../../src/utils";

const DynamicMapsWinRateLineChartCard = dynamic(
() => import("./charts/maps-win-rate-line-chart-card"),
Expand Down Expand Up @@ -72,7 +73,11 @@ const InnerMapStatsPage = ({
height={245}
width={245}
alt={selectedMap}
src={isOfficialMap(selectedMap) ? maps[selectedMap]?.url : ""}
src={
isOfficialMap(selectedMap)
? getIconsPathOnCDN(maps[selectedMap]?.url, "maps")
: ""
}
title={isOfficialMap(selectedMap) ? maps[selectedMap]?.url : ""}
/>
</Center>
Expand Down
9 changes: 7 additions & 2 deletions src/apis/coh3stats-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,22 @@ const getStatsData = async (
type: analysisType = "gameStats",
ock: string,
filters?: Array<analysisFilterType | analysisMapFilterType | "all">,
headers?: Record<string, string>,
) => {
const response = await fetch(getStatsUrl(startDate, endDate, type, ock, filters));
const data: getAnalysisStatsHttpResponse = await response.json();
const response = await fetch(getStatsUrl(startDate, endDate, type, ock, filters), {
headers: headers,
});

if (response.ok) {
const data: getAnalysisStatsHttpResponse = await response.json();
return data;
} else {
if (response.status === 500) {
const data = await response.json();
throw new Error(`Error getting the stats data: ${data.error}`);
}
console.log(response);
logger.error(`Error getting the stats data - status code ${response.status}`);
throw new Error(`Error getting the stats data`);
}
};
Expand Down
36 changes: 5 additions & 31 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export const sortArrayOfObjectsByTheirPropertyValue = (
export const getIconsPathOnCDN = (
// @ts-ignore
iconPath: string | StaticRequire | StaticImageData,
folder: "export" | "export_flatten" = "export",
folder: "export" | "export_flatten" | "maps" = "export",
) => {
if (typeof iconPath !== "string") {
return iconPath;
Expand All @@ -104,44 +104,18 @@ export const getIconsPathOnCDN = (
iconPath = iconPath.split(/[\\/]/).pop() || "";
}

if (!iconPath.endsWith(".png") && !iconPath.endsWith(".webp")) {
iconPath += ".png";
if (iconPath.endsWith(".png")) {
iconPath = iconPath.replace(".png", ".webp");
} else if (!iconPath.endsWith(".png") && !iconPath.endsWith(".webp")) {
iconPath += ".webp";
}

// Use .webp versions of all images
iconPath = iconPath.replace(".png", ".webp");

// Remove double // in case we have them in the path
const urlPath = `/${folder}/${iconPath}`.replace(/\/\//g, "/");

return internalSlash(`${config.CDN_ASSETS_HOSTING}${urlPath}`);
};

/**
* Get the path of the maps on our CDN hosting for images
* @param imagePath The path of the icon, can be full path or just filename.
*/
export const getMapsPathOnCDN = (
// @ts-ignore
imagePath: string | StaticRequire | StaticImageData,
) => {
if (typeof imagePath !== "string") {
return imagePath;
}

if (!imagePath.endsWith(".png") && !imagePath.endsWith(".webp")) {
imagePath += ".png";
}

// Use .webp versions of all images
imagePath = imagePath.replace(".png", ".webp");

// Remove double // in case we have them in the path
const urlPath = `/maps/${imagePath}`.replace(/\/\//g, "/");

return internalSlash(`${config.CDN_ASSETS_HOSTING}${urlPath}`);
};

// This is function where we don't care about VIEW but that it's mobile device
// https://stackoverflow.com/questions/11381673/detecting-a-mobile-browser/11381730#11381730
// prettier-ignore
Expand Down

0 comments on commit 3ac1796

Please sign in to comment.