script to update token category pages from existing categories

This commit is contained in:
saml33 2023-12-15 13:38:21 +11:00
parent 22d8a936c9
commit 4387e3aea1
4 changed files with 192 additions and 3 deletions

View File

@ -0,0 +1,168 @@
require('dotenv').config({ path: '.env.local' })
const {
createClient: createManagementClient,
} = require('contentful-management')
const { createClient: createDeliveryClient } = require('contentful')
const contentfulClient = createDeliveryClient({
space: process.env.NEXT_PUBLIC_CONTENTFUL_SPACE_ID,
accessToken: process.env.NEXT_PUBLIC_CONTENTFUL_ACCESS_TOKEN,
})
const managementClient = createManagementClient({
accessToken: process.env.NEXT_PUBLIC_CONTENTFUL_MANAGEMENT_TOKEN,
})
async function updateEntriesForTags() {
try {
const existingTags = await fetchExistingTags()
const existingTokenCategories = await fetchExistingTokenCategories()
// delete token categories not present in existingTags
await Promise.all(
existingTokenCategories.map(async (category) => {
if (!existingTags.includes(category)) {
await deleteTokenCategoryPage(category)
}
}),
)
// create or update entries for each existingTag
await Promise.all(
existingTags.map(async (tag) => {
await createEntryForNewTag(tag)
}),
)
console.log('contentful entries updated successfully.')
} catch (error) {
console.error('error updating contentful entries:', error.message)
}
}
async function fetchExistingTags() {
try {
const space = await managementClient.getSpace(
process.env.NEXT_PUBLIC_CONTENTFUL_SPACE_ID,
)
const environment = await space.getEnvironment('master')
const contentType = await environment.getContentType('token')
const tagsField = contentType.fields.find((field) => field.id === 'tags')
const tags = tagsField.items.validations[0].in
return tags
} catch (error) {
console.error(
'error fetching existing tags from token model:',
error.message,
)
return []
}
}
async function fetchExistingTokenCategories() {
try {
const entries = await contentfulClient.getEntries({
content_type: 'tokenCategory',
select: 'fields.category',
})
// extract slugs from the entries
const categories = entries.items.map((entry) => entry.fields.category)
return categories
} catch (error) {
console.error('error fetching existing token categories:', error.message)
return []
}
}
function transformToSlug(value) {
return value
.toLowerCase() // convert to lowercase
.replace(/[^a-zA-Z0-9\s]/g, '') // remove non-alphanumeric characters
.replace(/\s+/g, '-') // replace spaces with hyphens
.replace(/-+/g, '-') // replace consecutive hyphens with a single hyphen
}
async function createEntryForNewTag(tag) {
try {
const slug = transformToSlug(tag)
// fetch existing entry with the specified tag
const entry = await contentfulClient.getEntries({
content_type: 'tokenCategory',
'fields.slug[in]': slug,
})
if (entry.total) {
return
}
try {
const space = await managementClient.getSpace(
process.env.NEXT_PUBLIC_CONTENTFUL_SPACE_ID,
)
const environment = await space.getEnvironment('master')
// create a new entry
const entry = await environment.createEntry('tokenCategory', {
fields: {
category: { 'en-US': tag },
slug: { 'en-US': slug },
},
})
// publish the entry
await entry.publish()
console.log('entry created and published with ID:', entry.sys.id)
} catch (error) {
console.error('error creating and publishing entry:', error.message)
}
console.log(`entries updated for tag: ${tag}`)
} catch (error) {
console.error(`error updating entries for tag ${tag}:`, error.message)
}
}
async function getEntryIdByCategory(category) {
try {
const entries = await contentfulClient.getEntries({
content_type: 'tokenCategory',
'fields.category[in]': category,
select: 'sys.id',
limit: 1,
})
if (entries.items.length > 0) {
const entryId = entries.items[0].sys.id
console.log('entry id found:', entryId)
return entryId
} else {
console.log('no entry found for category:', category)
return null
}
} catch (error) {
console.error('error fetching entry id by category:', error.message)
return null
}
}
async function deleteTokenCategoryPage(category) {
try {
const entryId = await getEntryIdByCategory(category)
const space = await managementClient.getSpace(
process.env.NEXT_PUBLIC_CONTENTFUL_SPACE_ID,
)
const environment = await space.getEnvironment('master')
const entry = await environment.getEntry(entryId)
await entry.archive()
} catch (error) {
console.log(`error archiving ${category} page`)
}
}
updateEntriesForTags()

View File

@ -14,7 +14,8 @@
"lint": "eslint . --ext ts --ext tsx --ext js --ext jsx",
"test": "jest",
"test-all": "yarn lint && yarn type-check && yarn test",
"types:contentful": "export $(cat .env.local | awk '!/^\\s*#/' | awk '!/^\\s*$/'); npx cf-content-types-generator --spaceId $NEXT_PUBLIC_CONTENTFUL_SPACE_ID --token $NEXT_PUBLIC_CONTENTFUL_MANAGEMENT_TOKEN -o contentful/types -X && prettier --write contentful/types"
"types:contentful": "export $(cat .env.local | awk '!/^\\s*#/' | awk '!/^\\s*$/'); npx cf-content-types-generator --spaceId $NEXT_PUBLIC_CONTENTFUL_SPACE_ID --token $NEXT_PUBLIC_CONTENTFUL_MANAGEMENT_TOKEN -o contentful/types -X && prettier --write contentful/types",
"update-category-pages": "node contentful/updateCategoryPages.ts"
},
"engines": {
"node": ">=18.x"
@ -31,8 +32,10 @@
"@tanstack/react-query": "^5.8.4",
"@tippyjs/react": "^4.2.6",
"contentful": "^10.6.12",
"contentful-management": "^11.6.1",
"dayjs": "^1.11.10",
"decimal.js": "^10.4.3",
"dotenv": "^16.3.1",
"gsap": "^3.12.2",
"i18next": "^23.7.6",
"i18next-resources-to-backend": "^1.2.0",

File diff suppressed because one or more lines are too long

View File

@ -1727,7 +1727,7 @@ axios@^0.26.1:
dependencies:
follow-redirects "^1.14.8"
axios@^1.4.0, axios@^1.6.0:
axios@^1.4.0, axios@^1.6.0, axios@^1.6.2:
version "1.6.2"
resolved "https://registry.yarnpkg.com/axios/-/axios-1.6.2.tgz#de67d42c755b571d3e698df1b6504cde9b0ee9f2"
integrity sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==
@ -2209,6 +2209,19 @@ contentful-management@^11.0.1:
lodash.isplainobject "^4.0.6"
type-fest "^4.0.0"
contentful-management@^11.6.1:
version "11.6.1"
resolved "https://registry.yarnpkg.com/contentful-management/-/contentful-management-11.6.1.tgz#e772d963a1f4a74a3084f29e5afb31750bb4bd2e"
integrity sha512-ORocz/bupmrSUUcw5LAIL+RpabqALoDcqqb4KBC847uiFXfTrDkzLPEGuB46zR+8Fh08Lltz1tDw/TwRrXBVpQ==
dependencies:
"@contentful/rich-text-types" "^16.3.0"
"@types/json-patch" "0.0.30"
axios "^1.6.2"
contentful-sdk-core "^8.1.0"
fast-copy "^3.0.0"
lodash.isplainobject "^4.0.6"
type-fest "^4.0.0"
contentful-resolve-response@^1.3.6, contentful-resolve-response@^1.8.1:
version "1.8.1"
resolved "https://registry.yarnpkg.com/contentful-resolve-response/-/contentful-resolve-response-1.8.1.tgz#b44ff13e12fab7deb00ef6216d8a7171bdda0395"
@ -2559,6 +2572,11 @@ dom-helpers@^3.4.0:
dependencies:
"@babel/runtime" "^7.1.2"
dotenv@^16.3.1:
version "16.3.1"
resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-16.3.1.tgz#369034de7d7e5b120972693352a3bf112172cc3e"
integrity sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==
eastasianwidth@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb"