Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Created June 14, 2024 12:50
Show Gist options
  • Save SimeonGriggs/0df6d61a8d1d19dc5676d342ede953a6 to your computer and use it in GitHub Desktop.
Save SimeonGriggs/0df6d61a8d1d19dc5676d342ede953a6 to your computer and use it in GitHub Desktop.
Sanity Migration Tooling example for scripting new content from an API
import {
createIfNotExists,
defineMigration,
} from 'sanity/migrate'
type WordPressDataType =
| 'categories'
| 'posts'
| 'tags'
| 'users'
const BASE_URL = `https://blog.ted.com/wp-json/wp/v2`
const PER_PAGE = 100
const TYPE_MAPPINGS: Record<WordPressDataType, string> = {
categories: `category`,
posts: `post`,
tags: `tag`,
users: `author`,
}
export async function wpDataTypeFetch(
type: WordPressDataType,
page: number,
) {
const wpApiUrl = new URL(`${BASE_URL}/${type}`)
wpApiUrl.searchParams.set('page', page.toString())
wpApiUrl.searchParams.set('per_page', PER_PAGE.toString())
return await fetch(wpApiUrl.toString()).then((res) =>
res.status === 200 ? res.json() : null,
)
}
// Run with:
// npx sanity@latest migration run import-wp-json-data --no-dry-run -- --type=tags
export default defineMigration({
title: 'Import WP JSON data',
async *migrate() {
let wpType: WordPressDataType = process.argv
.find((a) => a.startsWith('--type='))
?.split('=')
.pop() as WordPressDataType
if (!wpType) {
throw new Error(
`Please specify a WordPress data type with --type, options include: categories, posts, tags, users`,
)
} else if (
['tags', 'categories', 'posts', 'users'].includes(
wpType,
) === false
) {
throw new Error(
`Invalid WordPress data type: ${wpType}`,
)
}
let page = 1
let hasMore = true
while (hasMore) {
const wpData = await wpDataTypeFetch(wpType, page)
if (Array.isArray(wpData) && wpData.length) {
for (const doc of wpData) {
yield createIfNotExists({
_id: `${TYPE_MAPPINGS[wpType]}-${doc.id}`,
_type: TYPE_MAPPINGS[wpType],
slug: {current: doc.slug},
})
}
page++
} else {
hasMore = false
break
}
}
return
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment