11import type { Metadata } from "next" ;
22import { apiPlugin , storyblokInit } from "@storyblok/react/rsc" ;
33
4+ import { SB_CACHE_VERSION_TAG } from "@/constants/cacheTags" ;
45import { COMPONENTS } from "@/constants/sbComponents" ;
56
67import { fetcher , getNextCachingParams } from "./utils" ;
78
9+ const LANGUAGE_CODES_REVALIDATE_SECONDS = 3600 ;
10+
811export const getStoryblokApi = storyblokInit ( {
912 accessToken : process . env . NEXT_PUBLIC_STORYBLOK_TOKEN ,
1013 use : [ apiPlugin ] ,
@@ -14,6 +17,7 @@ export const getStoryblokApi = storyblokInit({
1417export async function fetchStory (
1518 version : "draft" | "published" ,
1619 slug ?: string [ ] ,
20+ language ?: string ,
1721) {
1822 getStoryblokApi ( ) ;
1923 const correctSlug = `/${ slug ? slug . join ( "/" ) : "home" } ` ;
@@ -23,6 +27,10 @@ export async function fetchStory(
2327 token : process . env . NEXT_PUBLIC_STORYBLOK_TOKEN || "" ,
2428 } ) ;
2529
30+ if ( language ) {
31+ searchParams . set ( "language" , language ) ;
32+ }
33+
2634 const data = await fetcher (
2735 `${ process . env . NEXT_PUBLIC_STORYBLOK_API_GATE } /stories${ correctSlug } ?${ searchParams . toString ( ) } ` ,
2836 {
@@ -57,13 +65,44 @@ export async function fetchStories(
5765 return data ;
5866}
5967
68+ // Empty means "could not determine" as well as "no languages", and the caller must
69+ // strip nothing in either case. A hardcoded fallback would instead serve the wrong
70+ // story under a 200 — the failure nobody notices.
71+ export async function fetchLanguageCodes ( ) : Promise < string [ ] > {
72+ const searchParams = new URLSearchParams ( {
73+ token : process . env . NEXT_PUBLIC_STORYBLOK_TOKEN || "" ,
74+ } ) ;
75+
76+ try {
77+ const { data } = await fetcher (
78+ `${ process . env . NEXT_PUBLIC_STORYBLOK_API_GATE } /spaces/me?${ searchParams . toString ( ) } ` ,
79+ {
80+ method : "GET" ,
81+ next : {
82+ revalidate : LANGUAGE_CODES_REVALIDATE_SECONDS ,
83+ tags : [ SB_CACHE_VERSION_TAG ] ,
84+ } ,
85+ } ,
86+ ) ;
87+
88+ // `fetcher` does not check `response.ok`, so a 401 arrives here as a parsed body
89+ // with no `space` key rather than as a thrown error.
90+ return Array . isArray ( data ?. space ?. language_codes )
91+ ? data . space . language_codes
92+ : [ ] ;
93+ } catch {
94+ return [ ] ;
95+ }
96+ }
97+
6098export async function fetchStoryMetadata (
6199 version : "draft" | "published" ,
62100 slug ?: string [ ] ,
101+ language ?: string ,
63102) {
64103 const {
65104 data : { story } ,
66- } = await fetchStory ( version , slug ) ;
105+ } = await fetchStory ( version , slug , language ) ;
67106
68107 if ( ! story ) {
69108 console . log ( `missing metadata for story: ${ slug ?. join ( "/" ) } ` ) ;
0 commit comments