Skip to content

Commit 153c3af

Browse files
committed
feat: add getApiResponse
1 parent 4a7dadc commit 153c3af

File tree

9 files changed

+73
-16
lines changed

9 files changed

+73
-16
lines changed

src/app/api/hello/route.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { NextResponse } from 'next/server';
22

33
export async function GET() {
4-
return NextResponse.json({ hello: 'Next.js' });
4+
return NextResponse.json({ message: 'Test getApiResponse success!' });
55
}

src/app/error.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import WarningIcon from '@mui/icons-material/Warning';
44
import { Box, Button } from '@mui/material';
55
import * as React from 'react';
66

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

99
export default function Error({
1010
error,

src/app/not-found.tsx

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { Box } from '@mui/material';
22
import { Metadata } from 'next';
3-
import Link from 'next/link';
43
import * as React from 'react';
54
import { RiAlarmWarningFill } from 'react-icons/ri';
65

@@ -19,7 +18,7 @@ export default function NotFound() {
1918
/>
2019
<h1>Page Not Found</h1>
2120
<h5>change this in app/not-found.tsx</h5>
22-
<Link href='/'>Back to home</Link>
21+
<a href='/'>Back to home</a>
2322
</div>
2423
</Box>
2524
</main>

src/app/page.tsx

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ import { Box, Typography } from '@mui/material';
33
import Link from 'next/link';
44
import * as React from 'react';
55

6-
import PageFooter from '@/components/PageFooter';
7-
6+
import PageFooter from '@/component/PageFooter';
87
import { SITE_CONFIG } from '@/constant';
8+
import { getApiResponse } from '@/util/shared/get-api-response';
99

1010
// !STARTERCONF -> Select !STARTERCONF and CMD + SHIFT + F
1111
// Before you begin editing, follow all comments with `STARTERCONF`,
@@ -15,14 +15,19 @@ const loadDataFromApi = async (slug?: string) => {
1515
if (slug === 'testError500') {
1616
throw new Error('This is a ssr 500 test error');
1717
}
18+
19+
return await getApiResponse<{ version: string }>({
20+
apiEndpoint: 'https://registry.npmjs.org/react/latest',
21+
});
1822
};
1923

20-
export default async function HomePage({
21-
searchParams,
22-
}: {
24+
interface HomePageProps {
2325
searchParams: { [key: string]: string | undefined };
24-
}) {
25-
await loadDataFromApi(searchParams['slug']);
26+
}
27+
28+
export default async function HomePage({ searchParams }: HomePageProps) {
29+
const apiResult = await loadDataFromApi(searchParams['slug']);
30+
2631
return (
2732
<main>
2833
<section>
@@ -31,11 +36,19 @@ export default async function HomePage({
3136
<Typography variant='h5' component='h1' gutterBottom>
3237
{SITE_CONFIG.title}
3338
</Typography>
34-
3539
<Typography variant='subtitle2' gutterBottom>
3640
{SITE_CONFIG.description}
3741
</Typography>
3842

43+
<Typography
44+
variant='subtitle1'
45+
gutterBottom
46+
sx={{ color: 'green', mt: 3 }}
47+
>
48+
Get data from api test: The latest React version is{' '}
49+
{apiResult?.version}
50+
</Typography>
51+
3952
<Box sx={{ m: 5 }}>
4053
<Link
4154
href='https://github.com/AlexStack/nextjs-materia-mui-typescript-hook-form-scaffold-boilerplate-starter'
@@ -44,7 +57,6 @@ export default async function HomePage({
4457
See the Github repository page
4558
</Link>
4659
</Box>
47-
4860
<Box sx={{ m: 5 }}>
4961
<Link
5062
href='https://vercel.com/new/clone?s=https%3A%2F%2Fgithub.com%2FAlexStack%2Fnextjs-materia-mui-typescript-hook-form-scaffold-boilerplate-starter&showOptionalTeamCreation=false'
@@ -53,11 +65,9 @@ export default async function HomePage({
5365
Click here to deploy a demo site to your Vercel in 1 minute
5466
</Link>
5567
</Box>
56-
5768
<Box sx={{ m: 5 }}>
5869
<Link href='/test-page-not-exists'>Test 404 page not found</Link>
5970
</Box>
60-
6171
<Box sx={{ m: 5 }}>
6272
<Link href='/?slug=testError500'>Test 500 error page</Link>
6373
</Box>
File renamed without changes.

src/utils/__tests__/og.test.ts renamed to src/util/__tests__/og.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { openGraph } from '@/utils/og';
1+
import { openGraph } from '@/util/shared/og';
22

33
describe('Open Graph function should work correctly', () => {
44
it('should not return templateTitle when not specified', () => {
File renamed without changes.

src/util/shared/get-api-response.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { IS_PROD } from '@/constant';
2+
import { consoleLog } from '@/util/shared/console-log';
3+
4+
export const getApiResponse = async <T>({
5+
apiEndpoint,
6+
requestData,
7+
method = 'GET',
8+
revalidate = IS_PROD ? 3600 : 120, // cache data in seconds
9+
headers,
10+
}: {
11+
apiEndpoint: string;
12+
requestData?: BodyInit;
13+
method?: 'POST' | 'GET' | 'PUT' | 'DELETE';
14+
revalidate?: number;
15+
headers?: HeadersInit;
16+
}) => {
17+
try {
18+
const startTime = Date.now();
19+
const response = await fetch(apiEndpoint, {
20+
method,
21+
body: requestData,
22+
headers,
23+
next: {
24+
revalidate,
25+
},
26+
});
27+
if (!response.ok) {
28+
consoleLog('🚀 Debug getApiResponse requestData:', requestData);
29+
30+
throw new Error(
31+
`😢 getApiResponse failed: ${response.status}/${response.statusText} - ${apiEndpoint}`
32+
);
33+
}
34+
const duration = Date.now() - startTime;
35+
36+
consoleLog(
37+
`getApiResponse: ${(duration / 1000).toFixed(2)}s ${
38+
duration > 2000 ? '💔' : '-'
39+
} ${apiEndpoint}`
40+
);
41+
42+
return (await response.json()) as T;
43+
} catch (error) {
44+
consoleLog('getApiResponse error:', error);
45+
}
46+
47+
return null;
48+
};
File renamed without changes.

0 commit comments

Comments
 (0)