-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcharacters.api.ts
More file actions
95 lines (81 loc) · 2.49 KB
/
characters.api.ts
File metadata and controls
95 lines (81 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { LanguageVersion } from "@/store/global.store";
import { get } from "@/utils/object-utils";
import { getApiClient } from "@/lib/api-client";
const MARGONEM_CHARACTER_LIST_URL =
"https://public-api.margonem.pl/account/charlist";
const MARGONEM_CHARACTER_LIST_EN_URL =
"https://public-api.margonem.com/account/charlist";
export type MargonemCharacter = {
clan?: number;
clan_rank?: number;
gender?: "m" | "f";
icon: string;
id: number;
last?: number;
lvl: number;
nick: string;
prof: string;
world?: string;
};
export const normalizeCharacterList = (
characters: unknown,
): MargonemCharacter[] => {
if (!Array.isArray(characters)) {
return [];
}
return characters.filter((character): character is MargonemCharacter => {
return (
typeof character === "object" &&
character !== null &&
typeof character.id === "number" &&
typeof character.icon === "string" &&
typeof character.lvl === "number" &&
typeof character.nick === "string" &&
typeof character.prof === "string" &&
typeof character.world === "string"
);
});
};
type FetchCharacterListOptions = {
accountId: number;
world: string | undefined;
languageVersion: LanguageVersion;
};
export async function fetchCharacterList({
accountId,
world,
languageVersion,
}: FetchCharacterListOptions): Promise<MargonemCharacter[]> {
const margonemEntry = window.localStorage?.getItem("Margonem");
const parsed = margonemEntry ? JSON.parse(margonemEntry) : null;
const charlist = get(parsed, "charlist", null) as Record<
string,
MargonemCharacter[]
> | null;
const cached = accountId
? normalizeCharacterList(charlist?.[accountId] ?? null)
: [];
if (cached.length > 0) {
return cached
.filter((character) => character.world === world)
.sort((a, b) => b.lvl - a.lvl);
}
const hs3 = window.getCookie?.("hs3");
const url =
languageVersion === LanguageVersion.PL
? MARGONEM_CHARACTER_LIST_URL
: MARGONEM_CHARACTER_LIST_EN_URL;
if (!hs3) {
throw new Error("Missing required authentication cookie");
}
const client = getApiClient("public");
const response = await client.get<MargonemCharacter[]>(`${url}?hs3=${hs3}`, {
withCredentials: true,
});
if (!response.data || response.data.length === 0) {
throw new Error("Empty character list received from API");
}
return normalizeCharacterList(response.data)
.filter((character) => character.world === world)
.sort((a, b) => b.lvl - a.lvl);
}