Skip to content

Instantly share code, notes, and snippets.

@onefriendaday
Created March 19, 2019 15:37
Show Gist options
  • Save onefriendaday/9aedcad4d98ffdf4fe33fc1b43ae29f6 to your computer and use it in GitHub Desktop.
Save onefriendaday/9aedcad4d98ffdf4fe33fc1b43ae29f6 to your computer and use it in GitHub Desktop.
Creates or updates content of folders that are existing
const StoryblokClient = require('storyblok-js-client')
const Storyblok = new StoryblokClient({
oauthToken: PROTECTED_VAR
})
const sourceSpaceId = SOURCE_SPACE_ID
const targetSpaceId = TARGET_SPACE_ID
const Sync = {
getAll(page) {
return Storyblok.get('spaces/' + sourceSpaceId + '/stories', {
per_page: 25,
story_only: 1,
page: page
})
},
async processAllStories(){
var targetFolders = await Storyblok.get(`spaces/${targetSpaceId}/stories`, {
folder_only: 1,
per_page: 1000,
sort_by: 'slug:asc'
})
var folderMapping = {}
for (var i = 0; i < targetFolders.data.stories.length; i++) {
var folder = targetFolders.data.stories[i]
folderMapping[folder.full_slug] = folder.id
}
var page = 1
var res = await this.getAll(page)
var all = res.data.stories
var total = res.total
var lastPage = Math.ceil((res.total / 25))
while (page < lastPage){
page++
res = await this.getAll(page)
res.data.stories.forEach((story) => {
all.push(story)
})
}
for (var i = 0; i < all.length; i++) {
console.log('starting update ' + all[i].full_slug)
var storyResult = await Storyblok.get('spaces/' + sourceSpaceId + '/stories/' + all[i].id)
var sourceStory = storyResult.data.story
var slugs = sourceStory.full_slug.split('/')
var folderId = 0
if (slugs.length > 1) {
slugs.pop()
var folderSlug = slugs.join('/')
if (folderMapping[folderSlug]) {
folderId = folderMapping[folderSlug]
} else {
console.log('the folder does not exist ' + folderSlug)
continue;
}
}
sourceStory.parent_id = folderId
try {
var existingStory = await Storyblok.get('spaces/' + targetSpaceId + '/stories', {with_slug: all[i].full_slug})
if (existingStory.data.stories.length == 1) {
var updateResult = await Storyblok.put('spaces/' + targetSpaceId + '/stories/' + existingStory.data.stories[0].id, {
story: sourceStory,
force_update: '1'
})
console.log('updated ' + existingStory.data.stories[0].full_slug)
} else {
var updateResult = await Storyblok.post('spaces/' + targetSpaceId + '/stories', {
story: sourceStory
})
console.log('created ' + sourceStory.full_slug)
}
} catch(e) {
console.log(e)
}
}
return all
}
}
exports.handler = async function (event, context) {
await Sync.processAllStories()
return {
statusCode: '200',
body: JSON.stringify({success: 'Stories synced.'})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment