Files
web/apps/scandic-web/app/api/web/sitemap/sync.ts
Anton Gunnarsson 846fd904a6 Merged in feat/sw-2859-set-up-shared-trpc-package (pull request #2319)
feat(SW-2859): Create trpc package

* Add isEdge, safeTry and dataCache to new common package

* Add eslint and move prettier config

* Clean up tests

* Create trpc package and move initialization

* Move errors and a few procedures

* Move telemetry to common package

* Move tokenManager to common package

* Add Sentry to procedures

* Clean up procedures

* Fix self-referencing imports

* Add exports to packages and lint rule to prevent relative imports

* Add env to trpc package

* Add eslint to trpc package

* Apply lint rules

* Use direct imports from trpc package

* Add lint-staged config to trpc

* Move lang enum to common

* Restructure trpc package folder structure

* Fix lang imports


Approved-by: Linus Flood
2025-06-18 12:14:20 +00:00

79 lines
2.0 KiB
TypeScript

import { Region, Stack } from "contentstack"
import { createCounter } from "@scandic-hotels/common/telemetry"
import { env } from "@/env/server"
import type { SyncResponse } from "@/types/sitemap"
const environment = env.CMS_ENVIRONMENT
const stack = Stack({
api_key: env.CMS_API_KEY,
delivery_token: env.CMS_ACCESS_TOKEN,
branch: env.CMS_BRANCH,
environment,
region: Region.EU,
})
export async function contentstackSync(syncToken: string | null) {
const entries = []
const syncOptions = syncToken ? { sync_token: syncToken } : { init: true }
const entriesSyncCounter = createCounter("sitemap", "entries.sync")
const metricsEntriesSync = entriesSyncCounter.init({
environment,
...syncOptions,
})
metricsEntriesSync.start()
try {
let syncResponse: SyncResponse = await stack.sync(syncOptions)
entries.push(...syncResponse.items)
const entriesSyncPaginationCounter = createCounter(
"sitemap",
"entries.sync.pagination"
)
const metricsEntriesSyncPagination = entriesSyncPaginationCounter.init({
environment,
...syncOptions,
})
// Check if there is a pagination token, and fetch more data if needed
while (syncResponse.pagination_token && !syncResponse.sync_token) {
metricsEntriesSyncPagination.start({
paginationToken: syncResponse.pagination_token,
})
syncResponse = await stack.sync({
pagination_token: syncResponse.pagination_token,
})
entries.push(...syncResponse.items)
metricsEntriesSyncPagination.success({
paginationToken: syncResponse.pagination_token,
})
}
if (syncResponse.sync_token) {
metricsEntriesSync.success({
newSyncToken: syncResponse.sync_token,
entriesCount: entries.length,
})
return {
syncToken: syncResponse.sync_token,
entries,
}
} else {
throw new Error("No sync token received, something went wrong")
}
} catch (error) {
metricsEntriesSync.fail(error)
throw new Error("Failed to sync entries")
}
}