Skip to content

Commit

Permalink
fix: Job uses server's pagination (#315)
Browse files Browse the repository at this point in the history
  • Loading branch information
Liam-Zhao authored Oct 31, 2023
1 parent 9d74dd2 commit f93ae9a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 26 deletions.
51 changes: 28 additions & 23 deletions src/components/job/preheats/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,20 @@ import AddIcon from '@mui/icons-material/Add';
import MoreTimeIcon from '@mui/icons-material/MoreTime';
import { useNavigate, Link } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { getJobs, getJobsResponse } from '../../../lib/api';
import { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from '../../../lib/constants';
import { getDatetime, getPaginatedList } from '../../../lib/utils';
import { getJobs, JobsResponse } from '../../../lib/api';
import { DEFAULT_PAGE_SIZE } from '../../../lib/constants';
import { getDatetime } from '../../../lib/utils';

export default function Preheats() {
const [errorMessage, setErrorMessage] = useState(false);
const [errorMessageText, setErrorMessageText] = useState('');
const [preheatPage, setPreheatPage] = useState(1);
const [preheatTotalPages, setPreheatTotalPages] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [status, setStatus] = useState<string>('ALL');
const [shouldPoll, setShouldPoll] = useState(false);
const [openStatusSelect, setOpenStatusSelect] = useState(false);
const [allPreheats, setAllPreheats] = useState<getJobsResponse[]>([]);
const [allPreheats, setAllPreheats] = useState<JobsResponse[]>([]);

const navigate = useNavigate();

Expand All @@ -55,14 +56,18 @@ export default function Preheats() {
setIsLoading(true);

const jobs = await getJobs({
page: 1,
per_page: MAX_PAGE_SIZE,
page: preheatPage,
per_page: DEFAULT_PAGE_SIZE,
state: status === 'ALL' ? undefined : status,
});

setAllPreheats(jobs.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()));
setAllPreheats(jobs.data);
setPreheatTotalPages(jobs.total_page || 1);

const states = jobs.data.filter(
(obj) => obj.result.State !== 'SUCCESS' && obj.result.State !== 'FAILURE',
).length;

const states = jobs.filter((obj) => obj.result.State !== 'SUCCESS' && obj.result.State !== 'FAILURE').length;
states === 0 ? setShouldPoll(false) : setShouldPoll(true);

setIsLoading(false);
Expand All @@ -73,23 +78,26 @@ export default function Preheats() {
}
}
})();
}, [status]);
}, [status, preheatPage]);

useEffect(() => {
if (shouldPoll) {
const pollingInterval = setInterval(() => {
const pollPreheat = async () => {
try {
const jobs = await getJobs({
page: 1,
per_page: MAX_PAGE_SIZE,
page: preheatPage,
per_page: DEFAULT_PAGE_SIZE,
state: status === 'ALL' ? undefined : status,
});
setAllPreheats(jobs.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()));

const states = jobs.filter(
setAllPreheats(jobs.data);
setPreheatTotalPages(jobs.total_page || 1);

const states = jobs.data.filter(
(obj) => obj.result.State !== 'SUCCESS' && obj.result.State !== 'FAILURE',
).length;

states === 0 ? setShouldPoll(false) : setShouldPoll(true);
} catch (error) {
if (error instanceof Error) {
Expand All @@ -106,7 +114,7 @@ export default function Preheats() {
clearInterval(pollingInterval);
};
}
}, [status, shouldPoll]);
}, [status, shouldPoll, preheatPage]);

const statusList = [
{ lable: 'Pending', name: 'PENDING' },
Expand All @@ -115,9 +123,6 @@ export default function Preheats() {
{ lable: 'Failure', name: 'FAILURE' },
];

const totalPage = Math.ceil(allPreheats.length / DEFAULT_PAGE_SIZE);
const currentPageData = getPaginatedList(allPreheats, preheatPage, DEFAULT_PAGE_SIZE);

const changeStatus = (event: any) => {
setStatus(event.target.value);
setShouldPoll(true);
Expand Down Expand Up @@ -209,15 +214,15 @@ export default function Preheats() {
</FormControl>
</Box>
<Divider />
{currentPageData.length === 0 ? (
{allPreheats.length === 0 ? (
<Box sx={{ height: '4rem', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
You don't have any preheat tasks.
</Box>
) : (
<>
{Array.isArray(currentPageData) &&
currentPageData.map((item, index) => {
return index !== currentPageData.length - 1 ? (
{Array.isArray(allPreheats) &&
allPreheats.map((item, index) => {
return index !== allPreheats.length - 1 ? (
<Box key={item.id}>
<Box sx={{ display: 'flex', p: '0.8rem', alignItems: 'center' }}>
<Box sx={{ display: 'flex', alignItems: 'flex-start', width: '60%' }}>
Expand Down Expand Up @@ -365,10 +370,10 @@ export default function Preheats() {
</>
)}
</Paper>
{totalPage > 1 ? (
{preheatTotalPages > 1 ? (
<Box display="flex" justifyContent="flex-end" sx={{ marginTop: theme.spacing(2) }}>
<Pagination
count={totalPage}
count={preheatTotalPages}
onChange={(_event: any, newPage: number) => {
setPreheatPage(newPage);
}}
Expand Down
17 changes: 14 additions & 3 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import queryString from 'query-string';
import { parseLinkHeader } from '@web3-storage/parse-link-header';

const API_URL = process.env.REACT_APP_API_URL || window.location.href;

Expand Down Expand Up @@ -655,7 +656,7 @@ interface getJobsParams {
state?: string;
}

export interface getJobsResponse {
export interface JobsResponse {
id: number;
created_at: string;
updated_at: string;
Expand Down Expand Up @@ -689,13 +690,23 @@ export interface getJobsResponse {
};
}

export async function getJobs(params?: getJobsParams): Promise<getJobsResponse[]> {
interface getJobsResponse {
data: JobsResponse[];
total_page?: number;
}

export async function getJobs(params?: getJobsParams): Promise<getJobsResponse> {
const url = params
? new URL(`/api/v1/jobs?${queryString.stringify(params)}`, API_URL)
: new URL('/api/v1/jobs', API_URL);

const response = await get(url);
return await response.json();
const data = await response.json();
const linkHeader = response.headers.get('link');
const links = parseLinkHeader(linkHeader || null);
const totalPage = Number(links?.last?.page);
const responses = { data: data, total_page: totalPage };
return responses;
}

interface getJobResponse {
Expand Down

0 comments on commit f93ae9a

Please sign in to comment.