Skip to content

Instantly share code, notes, and snippets.

@eladroz
Created April 4, 2022 06:38
Show Gist options
  • Save eladroz/250b3c803f3a545174cab790999e3e71 to your computer and use it in GitHub Desktop.
Save eladroz/250b3c803f3a545174cab790999e3e71 to your computer and use it in GitHub Desktop.
Contentful client - polling for updates
import { writeFileSync } from 'fs';
import contentful from 'contentful';
const isDev = process.env.NODE_ENV === 'development';
export const client = contentful.createClient({
accessToken: isDev ? import.meta.env.VITE_CONTENTFUL_PREVIEW_TOKEN :
import.meta.env.VITE_CONTENTFUL_DELIVERY_API_TOKEN,
space: import.meta.env.VITE_CONTENTFUL_SPACE_ID,
host: isDev ? 'preview.contentful.com' : 'cdn.contentful.com'
});
if (isDev) {
let currentSyncToken;
client.sync({initial: true})
.then(({nextSyncToken}) => {
currentSyncToken = nextSyncToken;
setInterval(() => {
client.sync({ nextSyncToken: currentSyncToken })
.then(({nextSyncToken}) => {
if (currentSyncToken === nextSyncToken) {
return;
}
currentSyncToken = nextSyncToken;
writeFileSync('./src/contentful/update', nextSyncToken);
});
}, 1000);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment