Skip to content

Instantly share code, notes, and snippets.

@roberto-butti
Created June 25, 2024 11:58
Show Gist options
  • Save roberto-butti/77165482a84277aeb3fc18c0b6efb071 to your computer and use it in GitHub Desktop.
Save roberto-butti/77165482a84277aeb3fc18c0b6efb071 to your computer and use it in GitHub Desktop.
Example for retrieving Storyblok stories via translated slugs and managing cache via StoryblokClient (and also with fetch function)
import StoryblokClient from "storyblok-js-client";
const at = process.env.STORYBLOK_ACCESS_TOKEN;
// initalizing the StoryblokClient using the cache option.
// The cache option affect the caching for the response
// if the cache type is set to memory,
// the response from the API call is cached internally
// to the StoryblokClient.
// The lifecycle of the response cache is the same of the StoryblokClient instance
// The response cache can be flushed via the `flushCache()` method
// The cache option in the StoryblokClient doesn't affect the cv parameter behaviour
const Storyblok = new StoryblokClient({
accessToken: at,
cache: {
type: "memory",
},
});
// initialize the cv parameter as 0 or undefined in order to obtain a new CV
let cvStoredForFetch = 0;
// fetching an article via fetch (calling directly the HTTP API, managing manually the parameters)
setInterval(getArticleByFetch, 1000);
/*
Fetching an article via StoryblokClient:
- automatically retry in case of Rate Limit;
- managing cached response if cache option is set,
- store automatically the CV parameter
*/
setInterval(getArticle, 1000);
setInterval(getHomeStory, 1000);
// Cleaning the cache every X seconds
setInterval(cleanCache, 5000);
async function refreshCv() {
/* 2 options for retrieving a new CV parameter
- using the spaces/me endpoint (the commented solution)
- setting the cache version as undefined, so that allows the next request to retrieve the CV paramenter
*/
// First option via spaces/me
//const response = await Storyblok.get("cdn/spaces/me");
//console.log("Resetting CV with " + response.data.space.version);
// Second option via resetting the cache version
Storyblok.setCacheVersion("undefined");
// and here i'm resetting the manual CV i have to manage becasue the use case i want to
//call directly the API via the JS fetch method:
cvStoredForFetch = 0;
}
function cleanCache() {
Storyblok.flushCache();
refreshCv();
console.log("🧹🧹🧹🧹🧹🧹🧹🧹🧹 Cache cleaned");
}
async function getHomeStory() {
console.time("APICALL getHomeStory");
const response = await Storyblok.get("cdn/stories/home", {
version: "published",
});
console.timeEnd("APICAL getHomeStory");
console.log("Storyblok.cacheVersions():", Storyblok.cacheVersion());
console.log("HIT:", response.headers["x-cache"]);
console.log("AGE:", response.headers.age);
}
function getTranslatedSlugByLang(array, lang) {
return array.find((element) => element.lang === lang);
}
async function getArticle() {
console.time("APICALL getArticle");
// Getting the translated slug (set also the language params in the case you need to retrieve via translatedSlug)
const translatedSlug = "/articles/benvenuti";
const language = "it";
const response = await Storyblok.get(`cdn/stories${translatedSlug}`, {
version: "published",
language: language,
});
console.timeEnd("APICALL getArticle");
console.log("Storyblok.cacheVersions():", Storyblok.cacheVersion());
console.log("HIT:", response.headers["x-cache"]);
console.log("AGE:", response.headers.age);
console.log(
"Translated slug (StoryblokClient)",
getTranslatedSlugByLang(response.data.story.translated_slugs, language)
.path,
getTranslatedSlugByLang(response.data.story.translated_slugs, language)
.name,
);
}
async function getArticleByFetch() {
console.time("APICALL getArticleByFetch");
const slug = "/articles/benvenuti";
const params = new URLSearchParams({
token: at,
language: "it",
version: "published",
cv: cvStoredForFetch,
});
const url = `https://api.storyblok.com/v2/cdn/stories${slug}?${params}`;
console.log(url);
const response = await fetch(url);
const responseJson = await response.json();
console.timeEnd("APICALL getArticleByFetch");
console.log("CV:", responseJson.cv);
cvStoredForFetch = responseJson.cv;
console.log("HIT:", response.headers.get("x-cache"));
console.log("AGE:", response.headers.get("age"));
console.log(
"Translated slug ()via fetch()",
getTranslatedSlugByLang(responseJson.story.translated_slugs, "it").path,
getTranslatedSlugByLang(responseJson.story.translated_slugs, "it").name,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment