-
-
Notifications
You must be signed in to change notification settings - Fork 196
/
useContributors.ts
73 lines (60 loc) 路 1.76 KB
/
useContributors.ts
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
import { useState } from "react";
import useSWR, { Fetcher } from "swr";
import { useRouter } from "next/router";
import publicApiFetcher from "lib/utils/public-api-fetcher";
import getFilterQuery from "lib/utils/get-filter-query";
interface PaginatedResponse {
readonly data: DbPRContributor[];
readonly meta: Meta;
}
/**
* Fetch contributors based on pull requests.
*
* @param intialLimit
* @param repoIds
* @param range
* @returns
*/
const useContributors = (intialLimit = 10, repoIds: number[] = [], range = 30) => {
const router = useRouter();
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(intialLimit);
const { filterName, selectedFilter } = router.query;
const topic = filterName as string;
const filterQuery = getFilterQuery(selectedFilter);
const query = new URLSearchParams(filterQuery);
if (Number.isNaN(Number(topic))) {
query.set("topic", topic);
}
if (page) {
query.set("page", `${page}`);
}
if (limit) {
query.set("limit", `${limit}`);
}
if (repoIds?.length > 0) {
query.delete("topic");
query.set("repoIds", repoIds.join(","));
}
if (query.get("repo")) {
query.delete("topic");
}
query.set("range", `${range}`);
const baseEndpoint = "contributors/search";
const endpointString = `${baseEndpoint}?${query.toString()}`;
const { data, error, mutate } = useSWR<PaginatedResponse, Error>(
endpointString,
publicApiFetcher as Fetcher<PaginatedResponse, Error>
);
return {
data: data?.data ?? [],
meta: data?.meta ?? { itemCount: 0, limit: 0, page: 0, hasNextPage: false, hasPreviousPage: false, pageCount: 0 },
isLoading: !error && !data,
isError: !!error,
mutate,
page,
setPage,
setLimit,
};
};
export default useContributors;