Skip to content

Commit

Permalink
feat: add getApiResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexStack committed Sep 24, 2023
1 parent 4a7dadc commit 153c3af
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 16 deletions.
2 changes: 1 addition & 1 deletion src/app/api/hello/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { NextResponse } from 'next/server';

export async function GET() {
return NextResponse.json({ hello: 'Next.js' });
return NextResponse.json({ message: 'Test getApiResponse success!' });
}
2 changes: 1 addition & 1 deletion src/app/error.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import WarningIcon from '@mui/icons-material/Warning';
import { Box, Button } from '@mui/material';
import * as React from 'react';

import { consoleLog } from '@/utils/console-log';
import { consoleLog } from '@/util/shared/console-log';

export default function Error({
error,
Expand Down
3 changes: 1 addition & 2 deletions src/app/not-found.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Box } from '@mui/material';
import { Metadata } from 'next';
import Link from 'next/link';
import * as React from 'react';
import { RiAlarmWarningFill } from 'react-icons/ri';

Expand All @@ -19,7 +18,7 @@ export default function NotFound() {
/>
<h1>Page Not Found</h1>
<h5>change this in app/not-found.tsx</h5>
<Link href='/'>Back to home</Link>
<a href='/'>Back to home</a>
</div>
</Box>
</main>
Expand Down
32 changes: 21 additions & 11 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { Box, Typography } from '@mui/material';
import Link from 'next/link';
import * as React from 'react';

import PageFooter from '@/components/PageFooter';

import PageFooter from '@/component/PageFooter';
import { SITE_CONFIG } from '@/constant';
import { getApiResponse } from '@/util/shared/get-api-response';

// !STARTERCONF -> Select !STARTERCONF and CMD + SHIFT + F
// Before you begin editing, follow all comments with `STARTERCONF`,
Expand All @@ -15,14 +15,19 @@ const loadDataFromApi = async (slug?: string) => {
if (slug === 'testError500') {
throw new Error('This is a ssr 500 test error');
}

return await getApiResponse<{ version: string }>({
apiEndpoint: 'https://registry.npmjs.org/react/latest',
});
};

export default async function HomePage({
searchParams,
}: {
interface HomePageProps {
searchParams: { [key: string]: string | undefined };
}) {
await loadDataFromApi(searchParams['slug']);
}

export default async function HomePage({ searchParams }: HomePageProps) {
const apiResult = await loadDataFromApi(searchParams['slug']);

return (
<main>
<section>
Expand All @@ -31,11 +36,19 @@ export default async function HomePage({
<Typography variant='h5' component='h1' gutterBottom>
{SITE_CONFIG.title}
</Typography>

<Typography variant='subtitle2' gutterBottom>
{SITE_CONFIG.description}
</Typography>

<Typography
variant='subtitle1'
gutterBottom
sx={{ color: 'green', mt: 3 }}
>
Get data from api test: The latest React version is{' '}
{apiResult?.version}
</Typography>

<Box sx={{ m: 5 }}>
<Link
href='https://github.com/AlexStack/nextjs-materia-mui-typescript-hook-form-scaffold-boilerplate-starter'
Expand All @@ -44,7 +57,6 @@ export default async function HomePage({
See the Github repository page
</Link>
</Box>

<Box sx={{ m: 5 }}>
<Link
href='https://vercel.com/new/clone?s=https%3A%2F%2Fgithub.com%2FAlexStack%2Fnextjs-materia-mui-typescript-hook-form-scaffold-boilerplate-starter&showOptionalTeamCreation=false'
Expand All @@ -53,11 +65,9 @@ export default async function HomePage({
Click here to deploy a demo site to your Vercel in 1 minute
</Link>
</Box>

<Box sx={{ m: 5 }}>
<Link href='/test-page-not-exists'>Test 404 page not found</Link>
</Box>

<Box sx={{ m: 5 }}>
<Link href='/?slug=testError500'>Test 500 error page</Link>
</Box>
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { openGraph } from '@/utils/og';
import { openGraph } from '@/util/shared/og';

describe('Open Graph function should work correctly', () => {
it('should not return templateTitle when not specified', () => {
Expand Down
File renamed without changes.
48 changes: 48 additions & 0 deletions src/util/shared/get-api-response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { IS_PROD } from '@/constant';
import { consoleLog } from '@/util/shared/console-log';

export const getApiResponse = async <T>({
apiEndpoint,
requestData,
method = 'GET',
revalidate = IS_PROD ? 3600 : 120, // cache data in seconds
headers,
}: {
apiEndpoint: string;
requestData?: BodyInit;
method?: 'POST' | 'GET' | 'PUT' | 'DELETE';
revalidate?: number;
headers?: HeadersInit;
}) => {
try {
const startTime = Date.now();
const response = await fetch(apiEndpoint, {
method,
body: requestData,
headers,
next: {
revalidate,
},
});
if (!response.ok) {
consoleLog('🚀 Debug getApiResponse requestData:', requestData);

throw new Error(
`😢 getApiResponse failed: ${response.status}/${response.statusText} - ${apiEndpoint}`
);
}
const duration = Date.now() - startTime;

consoleLog(
`getApiResponse: ${(duration / 1000).toFixed(2)}s ${
duration > 2000 ? '💔' : '-'
} ${apiEndpoint}`
);

return (await response.json()) as T;
} catch (error) {
consoleLog('getApiResponse error:', error);
}

return null;
};
File renamed without changes.

0 comments on commit 153c3af

Please sign in to comment.