1
+ import { notFound , redirect } from "next/navigation" ;
1
2
import { getNews } from "@/helpers/homepage" ;
2
3
import { SingleType } from "@/types/strapi" ;
3
4
@@ -9,18 +10,31 @@ 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
+ throw new Error ( "Failed to parse homepage data" ) ;
23
+ }
24
+
25
+ if ( ! homePageData ?. data . attributes . body ) {
18
26
return Response . json ( "Homepage contains no data" ) ;
19
27
}
20
28
29
+ if ( ! Array . isArray ( homePageData ?. data ?. attributes ?. body ) ) {
30
+ return Response . json ( "Body has no content" ) ;
31
+ }
32
+
21
33
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 [ ] ;
34
+ if ( "newsCount" in contentEntry && "headline" in contentEntry ) {
35
+ return { index : i , newsCount : contentEntry . newsCount , headline : contentEntry . headline } ;
36
+ }
37
+ return [ ] ;
24
38
} ) ;
25
39
26
40
for ( const newsSectionEntry of newsSections ) {
@@ -31,3 +45,14 @@ export async function GET() {
31
45
32
46
return Response . json ( homePageData . data . attributes ) ;
33
47
}
48
+
49
+ function handleHTTPError ( errorCode : number ) {
50
+ switch ( errorCode ) {
51
+ case 400 :
52
+ return notFound ( ) ;
53
+ case 500 :
54
+ return redirect ( "/error/500" ) ;
55
+ default :
56
+ throw new Error ( "Fetching homepage data failed with status: " + errorCode ) ;
57
+ }
58
+ }
0 commit comments