Skip to content

Commit

Permalink
feat: change how metrics is displayed
Browse files Browse the repository at this point in the history
  • Loading branch information
diced committed Jul 11, 2024
1 parent 7ec1d6f commit da729ab
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 24 deletions.
63 changes: 46 additions & 17 deletions src/components/pages/metrics/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Box, Button, Group, Loader, Modal, Paper, SimpleGrid, Text, Title } from '@mantine/core';
import { Box, Button, Group, Loader, Modal, Paper, SimpleGrid, Text, Title, Tooltip } from '@mantine/core';
import { DatePicker } from '@mantine/dates';
import { IconCalendarTime } from '@tabler/icons-react';
import { IconCalendarSearch, IconCalendarTime } from '@tabler/icons-react';
import { useState } from 'react';
import FilesUrlsCountGraph from './parts/FilesUrlsCountGraph';
import StatsCards from './parts/StatsCards';
Expand All @@ -11,14 +11,16 @@ import { useApiStats } from './useStats';

export default function DashboardMetrics() {
const [dateRange, setDateRange] = useState<[Date | null, Date | null]>([
new Date(Date.now() - 86400000),
new Date(Date.now() - 86400000 * 7),
new Date(),
]);
const [open, setOpen] = useState(false);
const [allTime, setAllTime] = useState(false);

const { data, isLoading } = useApiStats({
from: dateRange[0]?.toISOString() ?? undefined,
to: dateRange[1]?.toISOString() ?? undefined,
all: allTime,
});

return (
Expand All @@ -28,9 +30,12 @@ export default function DashboardMetrics() {
<DatePicker
type='range'
value={dateRange}
onChange={setDateRange}
onChange={(value) => {
setDateRange(value);
setAllTime(false);
}}
allowSingleDateInRange={false}
maxDate={new Date(Date.now() + 86400000)}
maxDate={new Date(Date.now() + 0)}
/>
</Paper>

Expand All @@ -43,26 +48,50 @@ export default function DashboardMetrics() {

<Group>
<Title>Metrics</Title>

<Button
size='compact-sm'
variant='outline'
leftSection={<IconCalendarTime size='1rem' />}
leftSection={<IconCalendarSearch size='1rem' />}
onClick={() => setOpen(true)}
>
Change Date Range
</Button>

<Text size='sm' c='dimmed'>
{dateRange[0]?.toLocaleDateString()}{' '}
{dateRange[1] ? `to ${dateRange[1]?.toLocaleDateString()}` : ''}
</Text>
{!allTime ? (
<Text size='sm' c='dimmed'>
{data?.length ? (
<>
{new Date(data?.[data.length - 1]?.createdAt).toLocaleDateString()}
{' to '}
{new Date(data?.[0]?.createdAt).toLocaleDateString()}{' '}
</>
) : (
<>
{dateRange[0]?.toLocaleDateString()}{' '}
{dateRange[1] ? `to ${dateRange[1]?.toLocaleDateString()}` : ''}
</>
)}
</Text>
) : (
<Text size='sm' c='dimmed'>
All Time
</Text>
)}
<Tooltip label='This may take longer than usual to load.'>
<Button
size='compact-sm'
variant='outline'
leftSection={<IconCalendarTime size='1rem' />}
onClick={() => setAllTime(true)}
>
Show All Time
</Button>
</Tooltip>
</Group>

<Box pos='relative' mih={300} my='sm'>
{isLoading ? (
<Loader />
) : data ? (
) : data?.length ? (
<div>
<StatsCards data={data!} />

Expand All @@ -73,14 +102,14 @@ export default function DashboardMetrics() {
<ViewsGraph metrics={data!} />
</SimpleGrid>

{/* :skull: this stops it from overflowing somehow */}
<SimpleGrid cols={1}>
<div>
<StorageGraph metrics={data!} />
</SimpleGrid>
</div>
</div>
) : (
<Text size='sm' c='red'>
Failed to load statistics for this time range.
Failed to load statistics for this time range. There may be no data available within the time
range specified. :(
</Text>
)}
</Box>
Expand Down
2 changes: 2 additions & 0 deletions src/components/pages/metrics/useStats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import useSWR from 'swr';
type ApiStatsOptions = {
from?: string;
to?: string;
all?: boolean;
};

const fetcher = async ({ options }: { options: ApiStatsOptions } = { options: {} }) => {
const searchParams = new URLSearchParams();
if (options.from) searchParams.append('from', options.from);
if (options.to) searchParams.append('to', options.to);
if (options.all) searchParams.append('all', 'true');

const res = await fetch(`/api/stats${searchParams.toString() ? `?${searchParams.toString()}` : ''}`);

Expand Down
18 changes: 11 additions & 7 deletions src/server/routes/api/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export type ApiStatsResponse = Metric[];
type Query = {
from?: string;
to?: string;
all?: string;
};

export const PATH = '/api/stats';
Expand All @@ -17,19 +18,22 @@ export default fastifyPlugin(
server.get<{ Querystring: Query }>(PATH, { preHandler: [userMiddleware] }, async (req, res) => {
if (!config.features.metrics) return res.forbidden('metrics are disabled');

const { from, to } = req.query;
const { from, to, all } = req.query;

const fromDate = from ? new Date(from) : new Date(Date.now() - 86400000);
const fromDate = from ? new Date(from) : new Date(Date.now() - 86400000 * 7); // defaults to a week ago
const toDate = to ? new Date(to) : new Date();

if (isNaN(fromDate.getTime()) || isNaN(toDate.getTime())) return res.badRequest('invalid date(s)');
if (!all && (isNaN(fromDate.getTime()) || isNaN(toDate.getTime())))
return res.badRequest('invalid date(s)');

const stats = await prisma.metric.findMany({
where: {
createdAt: {
gte: fromDate,
lte: toDate,
},
...(!all && {
createdAt: {
gte: fromDate,
lte: toDate,
},
}),
},
orderBy: {
createdAt: 'desc',
Expand Down

0 comments on commit da729ab

Please sign in to comment.