1
1
import { getNews } from "@/helpers/homepage" ;
2
2
import { SingleType } from "@/types/strapi" ;
3
+ import { notFound , redirect } from "next/navigation" ;
3
4
4
5
export async function GET ( ) {
5
6
const res = await fetch ( `${ process . env . CMS_API } /home?populate=deep` , {
@@ -9,18 +10,28 @@ export async function GET() {
9
10
} ) ;
10
11
11
12
if ( ! res . ok ) {
13
+ handleHTTPError ( res . status ) ;
12
14
throw new Error ( "Fetching single type component home failed" ) ;
13
15
}
14
16
15
- const homePageData = ( await res . json ( ) ) as SingleType ;
17
+ let homePageData : SingleType ;
16
18
17
- if ( ! homePageData . data . attributes . body ) {
19
+ try {
20
+ homePageData = ( await res . json ( ) ) as SingleType ;
21
+ } catch ( e ) {
22
+ console . log ( e ) ;
23
+ throw new Error ( "Failed to parse homepage data" ) ;
24
+ }
25
+
26
+ if ( ! homePageData ?. data . attributes . body ) {
18
27
return Response . json ( "Homepage contains no data" ) ;
19
28
}
20
29
21
30
const newsSections = homePageData . data . attributes . body . flatMap ( ( contentEntry , i ) => {
22
- if ( "newsCount" in contentEntry ) return { index : i , newsCount : contentEntry . newsCount , headline : contentEntry . headline } ;
23
- else return [ ] ;
31
+ if ( "newsCount" in contentEntry ) {
32
+ return { index : i , newsCount : contentEntry . newsCount , headline : contentEntry . headline } ;
33
+ }
34
+ return [ ] ;
24
35
} ) ;
25
36
26
37
for ( const newsSectionEntry of newsSections ) {
@@ -31,3 +42,14 @@ export async function GET() {
31
42
32
43
return Response . json ( homePageData . data . attributes ) ;
33
44
}
45
+
46
+ function handleHTTPError ( errorCode : number ) {
47
+ switch ( errorCode ) {
48
+ case 400 :
49
+ return notFound ( ) ;
50
+ case 500 :
51
+ return redirect ( "/error/500" ) ;
52
+ default :
53
+ throw new Error ( "Fetching homepage data failed with status: " + errorCode ) ;
54
+ }
55
+ }
0 commit comments