-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathuseBuilds.js
61 lines (52 loc) · 1.64 KB
/
useBuilds.js
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
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
import api from '@util/federalistApi';
import { REFETCH_INTERVAL, shouldScrollIntoView } from './utils';
// Assumes the order of builds is based on createdAt desc
export function getLatestBuildByBranch(builds) {
const latestBranches = [];
return builds.map((build) => {
if (build.completedAt && !latestBranches.includes(build.branch)) {
latestBranches.push(build.branch);
return { ...build, latestForBranch: true };
}
return { ...build, latestForBranch: false };
});
}
export function useBuilds(siteId) {
const { data, error, isPending, isPlaceholderData } = useQuery({
placeholderData: [],
queryKey: ['builds', parseInt(siteId, 10)],
queryFn: () =>
api.fetchBuilds({ id: siteId }).then((builds) => getLatestBuildByBranch(builds)),
refetchInterval: REFETCH_INTERVAL,
refetchIntervalInBackground: false,
});
return { data, error, isPending, isPlaceholderData };
}
export function useRebuild(siteId, buildId, ref) {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: ({ buildId, siteId }) => api.restartBuild(buildId, siteId),
onSuccess: () => {
// Scroll to build history container ref
// Invalidate and refetch
return Promise.all([
shouldScrollIntoView(ref),
queryClient.invalidateQueries({
queryKey: ['builds', parseInt(siteId, 10)],
}),
]);
},
});
async function rebuildBranch() {
return mutation.mutate({
buildId,
siteId,
});
}
return {
...mutation,
queryClient,
rebuildBranch,
};
}