Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storyblok cache tags #4

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,20 @@ export const transformId = (id) => {
}
}

export const transformStory = ({ id, ...story } = {}) => {
story.content = JSON.stringify(story.content)
story.full_slug = story.full_slug.replace(/^\/|\/$/g, '')
export const getCacheTag = (story) => {
return story.id ? `SB${story.id}` : ''
}

export const transformStory = (story = {}) => {
const storyParams = {
content: JSON.stringify(story.content),
full_slug: story.full_slug.replace(/^\/|\/$/g, ''),
cache_tag: getCacheTag(story)
}
const transformedStory = Object.assign({}, story, storyParams)
return {
...transformId(id),
body: story
...transformId(story.id),
body: transformedStory
}
}

Expand Down Expand Up @@ -131,12 +139,14 @@ export const log = (string) => {
console.log('📖 : ' + string) // eslint-disable-line no-console
}

export const cacheInvalidate = async () => {
export const cacheInvalidate = async (config, story = null) => {
if (config.invalidate) {
log(`Invalidating cache... (${config.invalidate})`)
await rp({
uri: config.invalidate
})
let url = config.invalidate
if (story && story.body.cache_tag) {
url += story.body.cache_tag;
}
log(`Invalidating cache... (${url})`)
await rp({ uri: url })
log('Invalidated cache ✅')
}
}
Expand Down
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ module.exports = ({ config }) => {

setConfig(config)
initStoryblokClient(config)
seedDatabase(db, config)


api.get('/story/', async (req, res) => {
const story = await getStory(db, 'home')
Expand Down Expand Up @@ -44,7 +44,8 @@ module.exports = ({ config }) => {

api.post('/hook', protectRoute(config), async (req, res) => {
try {
await handleHook(db, config, req.body)
const { invalidate = false } = req.query
await handleHook(db, config, req.body, invalidate)
apiStatus(res)
} catch (error) {
apiStatus(res, {
Expand Down
33 changes: 27 additions & 6 deletions sync.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { storyblokClient } from './storyblok'
import { log, createIndex, deleteIndex, createBulkOperations, transformId, transformStory, cacheInvalidate } from './helpers'
import {
log,
createIndex,
deleteIndex,
createBulkOperations,
transformId,
transformStory,
cacheInvalidate,
getCacheTag
} from './helpers'

function indexStories ({ db, stories = [] }) {
const bulkOps = createBulkOperations(stories)
Expand Down Expand Up @@ -28,6 +37,7 @@ async function syncStories ({ db, page = 1, perPage = 100, environment = null })
...story,
full_slug: fullSlug,
real_path: fullSlug.substr(0, 1) === '/' ? fullSlug : `/${fullSlug}`,
cache_tag: getCacheTag(story),
folder: fullSlug.lastIndexOf('/') !== -1 ? fullSlug.substring(0, fullSlug.lastIndexOf('/')) : null
}
})
Expand All @@ -47,14 +57,22 @@ async function syncStories ({ db, page = 1, perPage = 100, environment = null })
const fullSync = async (db, config) => {
log('Syncing published stories!')

await db.indices.delete(deleteIndex())
await db.indices.create(createIndex())
await syncStories({ db, perPage: config.storyblok.perPage, environment: config.storyblok.environment })
// This will call the storyblok API, load up the stories, and then return a promise to index them
// Tested with ngrok
try {
const indexStories = syncStories({ db, perPage: config.storyblok.perPage, environment: config.storyblok.environment })
await db.indices.delete(deleteIndex())
await db.indices.create(createIndex())
await indexStories
} catch(e) {
console.error(e)
}
}

const handleHook = async (db, config, params) => {
const handleHook = async (db, config, params, invalidate) => {
const cv = Date.now() // bust cache
const { story_id: id, action } = params
let invalidatedStory = null

switch (action) {
case 'published':
Expand Down Expand Up @@ -82,6 +100,7 @@ const handleHook = async (db, config, params) => {
}

const publishedStory = transformStory(story)
invalidatedStory = publishedStory

await db.index(publishedStory)
log(`Published ${story.full_slug}`)
Expand All @@ -99,7 +118,9 @@ const handleHook = async (db, config, params) => {
default:
break
}
await cacheInvalidate(config.storyblok)
if (invalidate) {
await cacheInvalidate(config.storyblok, invalidatedStory)
}
}

const seedDatabase = async (db, config) => {
Expand Down