-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.high-score.ts
More file actions
78 lines (69 loc) · 2.18 KB
/
api.high-score.ts
File metadata and controls
78 lines (69 loc) · 2.18 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
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import type { InferRequestType, InferResponseType } from 'hono/client';
import { hc } from 'hono/client';
import { useMonitor } from './monitor.use-monitor';
import { getServerUrl } from '../config';
import type { ServerApi } from 'types.shared';
const serverUrl = getServerUrl();
const { $get, $post } = hc<ServerApi>(serverUrl)['high-score'];
const HIGH_SCORE_QUERY_KEY = 'highScore';
export type GetHighScoreApi = ReturnType<typeof useGetHighScoreApi>;
export function useGetHighScoreApi() {
const { captureException } = useMonitor();
return useQuery({
queryKey: [HIGH_SCORE_QUERY_KEY],
queryFn: async () => {
return $get()
.then(async (res) => {
if (!res.ok) {
const error = await parseError(res);
throw error;
}
return res.json();
})
.catch((error) => {
captureException(error);
return null;
});
},
});
}
export type UpdateHighScoreApi = ReturnType<typeof useUpdateHighScoreApi>;
export function useUpdateHighScoreApi() {
const queryClient = useQueryClient();
const { captureException } = useMonitor();
return useMutation<
InferResponseType<typeof $post>,
Error,
InferRequestType<typeof $post>['json']
>({
mutationFn: async (updateHighScore) => {
return $post({ json: updateHighScore }).then(async (res) => {
if (!res.ok) {
const error = await parseError(res);
throw error;
}
return res.json();
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [HIGH_SCORE_QUERY_KEY] });
},
onError: (error) => {
captureException(error);
},
});
}
const DEFAULT_MESSAGE =
'Request to high score failed.\nPlease check your connection and try again.';
const parseError = async (err: unknown): Promise<Error> => {
if (err instanceof Response) {
const json = await err.json();
const message = json?.message || DEFAULT_MESSAGE;
return new Error(message, { cause: err });
}
if (err instanceof Error) {
return err;
}
return new Error(DEFAULT_MESSAGE, { cause: err });
};