Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions locales/en/allLaunches.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,9 @@
"title": "Lançamentos",
"description": "Acompanhe os lançamentos e os dados de cada missão."
}
},
"actions": {
"refresh": "Refresh launches",
"refreshSuccess": "Data updated"
}
}
4 changes: 4 additions & 0 deletions locales/es/allLaunches.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,9 @@
"title": "Lançamentos",
"description": "Acompanhe os lançamentos e os dados de cada missão."
}
},
"actions": {
"refresh": "Actualizar lanzamientos",
"refreshSuccess": "Datos actualizados"
}
}
4 changes: 4 additions & 0 deletions locales/pt/allLaunches.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,9 @@
"title": "Lançamentos",
"description": "Acompanhe os lançamentos e os dados de cada missão."
}
},
"actions": {
"refresh": "Atualizar lançamentos",
"refreshSuccess": "Dados atualizados"
}
}
47 changes: 44 additions & 3 deletions pages/launches/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useAllLaunches } from '@/src/core/services/launches/useGetAllLaunches.service';
import { slugifyLaunchName } from '@/src/shared/utils/formatters.utils';
import { Alert, Box, CircularProgress, Container, Stack, Typography } from '@mui/material';
import { Alert, Box, Button, CircularProgress, Container, Snackbar } from '@mui/material';
import RefreshIcon from '@mui/icons-material/Refresh';
import type {} from '@mui/lab/themeAugmentation';
import useTranslation from 'next-translate/useTranslation';
import LaunchSummaryCard from '@/src/components/LaunchCard/LaunchSummaryCard';
Expand All @@ -17,9 +18,22 @@ const SCROLL_POSITION_KEY = 'zenith-launches-scroll';

// TODO mover textos para arquivo de tradução
export default function LaunchesPage() {
const { launches, isLoadingAllLaunches, error } = useAllLaunches();
const { launches, isLoadingAllLaunches, isRefreshingLaunches, refreshLaunches, error } = useAllLaunches();
const router = useRouter();
const { t } = useTranslation();
const [isRefreshSnackbarOpen, setIsRefreshSnackbarOpen] = useState(false);

const handleRefreshLaunches = async () => {
const succeeded = await refreshLaunches();
if (succeeded) {
setIsRefreshSnackbarOpen(true);
}
};

const handleCloseRefreshSnackbar = (_event?: React.SyntheticEvent | Event, reason?: string) => {
if (reason === 'clickaway') return;
setIsRefreshSnackbarOpen(false);
};

useEffect(() => {
if (isLoadingAllLaunches || launches.length === 0) return;
Expand Down Expand Up @@ -61,6 +75,19 @@ export default function LaunchesPage() {
/>
<Box sx={pageBackgroundSx}>
<Container maxWidth="lg" sx={containerSx}>
{!isLoadingAllLaunches && (
<Box sx={toolbarSx}>
<Button
variant="outlined"
onClick={handleRefreshLaunches}
disabled={isRefreshingLaunches}
startIcon={isRefreshingLaunches ? <CircularProgress size={18} color="inherit" /> : <RefreshIcon />}
>
{t(LOCALE.LAUNCHES.ACTIONS.REFRESH)}
</Button>
</Box>
)}

{error && (
<Alert severity="error" sx={errorAlertSx}>
{error}
Expand Down Expand Up @@ -89,13 +116,27 @@ export default function LaunchesPage() {
)}
</Container>
</Box>

<Snackbar
open={isRefreshSnackbarOpen}
autoHideDuration={3000}
onClose={handleCloseRefreshSnackbar}
anchorOrigin={snackbarAnchorOrigin}
>
<Alert onClose={handleCloseRefreshSnackbar} severity="success" variant="filled" sx={snackbarAlertSx}>
{t(LOCALE.LAUNCHES.ACTIONS.REFRESH_SUCCESS)}
</Alert>
</Snackbar>
</>
);
}

const pageBackgroundSx = { backgroundColor: BACKGROUND_COLOR };
const containerSx = { py: 6 };
const toolbarSx = { display: 'flex', justifyContent: 'flex-end', mb: 3 };
const errorAlertSx = { mb: 3 };
const snackbarAnchorOrigin = { vertical: 'bottom', horizontal: 'center' } as const;
const snackbarAlertSx = { width: '100%' };
const loadingBoxSx = { display: 'flex', justifyContent: 'center', py: 10 };
const launchesGridSx = {
display: 'grid',
Expand Down
17 changes: 15 additions & 2 deletions src/core/api/launches/launches-api.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import { environment } from '@/src/environments/environment';
import { LaunchRecord, LaunchSummary } from '@/src/shared/types/api/launches-api.types';

export const getAllLaunches = async (signal?: AbortSignal): Promise<LaunchSummary[]> => {
const response = await fetch(environment.launchesEndpoints.launches.all, { signal });
type GetAllLaunchesApiOptions = {
signal?: AbortSignal;
bypassCache?: boolean;
};

export const getAllLaunches = async ({ signal, bypassCache = false }: GetAllLaunchesApiOptions = {}): Promise<
LaunchSummary[]
> => {
const url = new URL(environment.launchesEndpoints.launches.all);
if (bypassCache) {
// O GitHub Pages responde com max-age=600: sem isso o navegador/CDN devolvem a resposta em cache.
url.searchParams.set('t', String(Date.now()));
}

const response = await fetch(url, { signal, cache: bypassCache ? 'no-store' : 'default' });
if (!response.ok) {
throw new Error('Failed to fetch launches data');
}
Expand Down
16 changes: 14 additions & 2 deletions src/core/services/launches.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,21 @@ import {
getLaunchContent as getLaunchContentApi
} from '@/src/core/api/launches/launches-api.service';
import { LaunchRecord, LaunchSummary } from '@/src/shared/types/api/launches-api.types';
import { readCachedLaunches, saveCachedLaunches } from './launches/launchesCache';

export const getAllLaunches = async (): Promise<LaunchSummary[]> => {
return getAllLaunchesApi();
type GetAllLaunchesOptions = {
forceRefresh?: boolean;
};

export const getAllLaunches = async ({ forceRefresh = false }: GetAllLaunchesOptions = {}): Promise<LaunchSummary[]> => {
if (!forceRefresh) {
const cached = readCachedLaunches();
if (cached) return cached;
}

const data = await getAllLaunchesApi({ bypassCache: forceRefresh });
saveCachedLaunches(data);
return data;
};

export const getLaunchContent = async (downloadUrl: string): Promise<LaunchRecord[]> => {
Expand Down
45 changes: 45 additions & 0 deletions src/core/services/launches/launchesCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { LaunchSummary } from '@/src/shared/types/api/launches-api.types';

export const LAUNCHES_STORAGE_KEY = 'zenith-launches';
export const LAUNCHES_CACHE_TTL_MS = 24 * 60 * 60 * 1000;

type CachedLaunches = {
savedAt: number;
data: LaunchSummary[];
};

const isStorageAvailable = () => typeof window !== 'undefined' && Boolean(window.localStorage);

export const readCachedLaunches = (): LaunchSummary[] | null => {
if (!isStorageAvailable()) return null;

try {
const raw = localStorage.getItem(LAUNCHES_STORAGE_KEY);
if (!raw) return null;

const parsed: CachedLaunches = JSON.parse(raw);
const isValid = Array.isArray(parsed?.data) && typeof parsed?.savedAt === 'number';
const isExpired = Date.now() - parsed.savedAt > LAUNCHES_CACHE_TTL_MS;

if (!isValid || isExpired) {
localStorage.removeItem(LAUNCHES_STORAGE_KEY);
return null;
}

return parsed.data;
} catch {
localStorage.removeItem(LAUNCHES_STORAGE_KEY);
return null;
}
};

export const saveCachedLaunches = (data: LaunchSummary[]) => {
if (!isStorageAvailable()) return;

try {
const payload: CachedLaunches = { savedAt: Date.now(), data };
localStorage.setItem(LAUNCHES_STORAGE_KEY, JSON.stringify(payload));
} catch {
// Storage cheio ou indisponível (ex.: modo privado): segue sem cache.
}
};
64 changes: 37 additions & 27 deletions src/core/services/launches/useGetAllLaunches.service.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,53 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { LaunchSummary } from '@/src/shared/types/api/launches-api.types';
import { getAllLaunches } from '../launches.service';

export const useAllLaunches = () => {
const [launches, setLaunches] = useState<LaunchSummary[]>([]);
const [isLoadingAllLaunches, setIsLoadingAllLaunches] = useState(true);
const [isRefreshingLaunches, setIsRefreshingLaunches] = useState(false);
const [error, setError] = useState<string | null>(null);
const isMountedRef = useRef(true);

useEffect(() => {
const controller = new AbortController();

const fetchLaunches = async () => {
setIsLoadingAllLaunches(true);
setError(null);

try {
const rawData = await getAllLaunches();
if (!controller.signal.aborted) {
setLaunches(rawData);
}
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') {
return;
}
const fetchLaunches = useCallback(async (forceRefresh: boolean): Promise<boolean> => {
setError(null);

try {
const rawData = await getAllLaunches({ forceRefresh });
if (isMountedRef.current) {
setLaunches(rawData);
}
return true;
} catch (err) {
if (isMountedRef.current) {
setError(err instanceof Error ? err.message : 'Ocorreu um erro inesperado');
} finally {
if (!controller.signal.aborted) {
setIsLoadingAllLaunches(false);
}
}
};
return false;
}
}, []);

fetchLaunches();
useEffect(() => {
isMountedRef.current = true;

fetchLaunches(false).finally(() => {
if (isMountedRef.current) {
setIsLoadingAllLaunches(false);
}
});

return () => {
controller.abort();
isMountedRef.current = false;
};
}, []);

return { launches, isLoadingAllLaunches, error };
}, [fetchLaunches]);

const refreshLaunches = useCallback(async (): Promise<boolean> => {
setIsRefreshingLaunches(true);
const succeeded = await fetchLaunches(true);
if (isMountedRef.current) {
setIsRefreshingLaunches(false);
}
return succeeded;
}, [fetchLaunches]);

return { launches, isLoadingAllLaunches, isRefreshingLaunches, refreshLaunches, error };
};
4 changes: 4 additions & 0 deletions src/shared/consts/locales.const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ export const LAUNCHES = {
TITLE: 'allLaunches:metaTags.title',
DESCRIPTION: 'allLaunches:metaTags.description',
SUBTITLE: 'allLaunches:metaTags.subtitle'
},
ACTIONS: {
REFRESH: 'allLaunches:actions.refresh',
REFRESH_SUCCESS: 'allLaunches:actions.refreshSuccess'
}
} as const;

Expand Down
Loading