Skip to content

Instantly share code, notes, and snippets.

@mattgrah-am
Created April 6, 2023 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattgrah-am/4ced19d9f8124cb7d8789c303b5c7049 to your computer and use it in GitHub Desktop.
Save mattgrah-am/4ced19d9f8124cb7d8789c303b5c7049 to your computer and use it in GitHub Desktop.
index.ts
import StoryblokClient, { ISbStories } from "storyblok-js-client";
import algoliasearch from "algoliasearch";
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig();
const indexerSecret = config.algolia.indexerSecret;
// Check sb indexer secret matches .env secret
const { token } = getQuery(event);
if (!token || indexerSecret !== token) {
throw createError({
statusCode: 401,
statusMessage: "You are not allowed to access this resource",
});
}
// init algolia
const applicationId = config.algolia.applicationId;
const algoliaWriteApiKey = config.algolia.writeApiKey;
const algolia = algoliasearch(
String(applicationId),
String(algoliaWriteApiKey)
);
// init storyblok
const storyblok = new StoryblokClient({
accessToken: config.algolia.sbAccessToken,
region: "us",
});
// get all sb data **excluding author data
try {
const response: ISbStories = await storyblok.get(`cdn/stories/`, {
version: "published",
excluding_slugs: "authors/*",
cv: Date.now(),
});
const contentRequests = response.data.stories;
const index = algolia.initIndex(String(config.algolia.indexName));
const storyblokUUID: string[] = [];
const responseMessage: string[] = [];
contentRequests.forEach((content: any) => {
content.objectID = content.uuid;
storyblokUUID.push(content.uuid);
});
// send all new / updated data to algolia
try {
await Promise.all(contentRequests);
await index
.saveObjects(contentRequests, {
autoGenerateObjectIDIfNotExist: false,
})
.wait();
responseMessage.push(
`Index stored with ${contentRequests.length} Entries.`
);
console.log(`Index stored with ${contentRequests.length} Entries.`);
} catch (error: any) {
throw createError({
statusCode: error.statusCode || 500,
statusMessage:
error.message || error.statusMessage || "Internal Server Error",
});
}
// compare sb id list to algolia id list and delete any id's that are in the algolia list that isn't in the sb list
try {
let algoliaData: any = [];
await index.browseObjects({
batch: (batch) => (algoliaData = algoliaData.concat(batch)),
});
const algoliaObjectId: string[] = [];
algoliaData.forEach((record: any) => {
algoliaObjectId.push(record.objectID);
});
const filteredId = algoliaObjectId.filter(
(el) => !storyblokUUID.includes(el)
);
if (filteredId.length === 0) {
responseMessage.push("no records to delete");
console.log("no records to delete");
} else {
try {
await index.deleteObjects(filteredId).wait();
responseMessage.push(
`${filteredId.length} ${
filteredId.length === 1 ? "record" : "records"
} deleted`
);
console.log(
`${filteredId.length} ${
filteredId.length === 1 ? "record" : "records"
} deleted`
);
} catch (error: any) {
console.log(error);
throw createError({
statusCode: error.statusCode || 500,
statusMessage:
error.message || error.statusMessage || "Internal Server Error",
});
}
}
} catch (error: any) {
console.log(error);
throw createError({
statusCode: error.statusCode || 500,
statusMessage:
error.message || error.statusMessage || "Internal Server Error",
});
}
return (
responseMessage.join(" ") +
" - Algolia indexed with the data from Storyblok!"
);
} catch (error: any) {
console.log(error);
throw createError({
statusCode: error.statusCode || 500,
statusMessage:
error.message || error.statusMessage || "Internal Server Error",
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment