Add preview handling

This commit is contained in:
nicwands
2026-06-01 11:08:03 -04:00
parent ef70a0c756
commit 6776a14757
18 changed files with 1186 additions and 14 deletions

View File

@@ -5,7 +5,105 @@ export const strapiClient = strapi({
auth: import.meta.env.VITE_STRAPI_API_TOKEN,
})
export const getGlobal = async () => {
const globalManager = strapiClient.single('global')
return await globalManager.find()
/**
* Enhanced fetch function with preview support
* @param {string} contentType - The Strapi content type (e.g., 'global', 'articles')
* @param {object} options - Fetch options including preview settings
* @param {boolean} options.isPreview - Whether this is a preview request
* @param {string} options.status - Content status ('draft' or 'published')
* @param {boolean} options.isSingle - Whether this is a single type or collection
* @param {object} options.params - Additional query parameters
* @returns {Promise} Strapi response
*/
export const fetchWithPreview = async (contentType, options = {}) => {
const {
isPreview = false,
status = 'published',
isSingle = false,
params = {},
...otherOptions
} = options
const queryParams = { ...params }
const headers = {}
// Add status parameter for draft content in preview mode
if (isPreview && status) {
queryParams.status = status
}
// Enable content source maps for Live Preview
if (isPreview) {
headers['strapi-encode-source-maps'] = 'true'
}
// Disable caching for preview requests
if (isPreview) {
headers['Cache-Control'] = 'no-cache'
}
try {
if (isSingle) {
const manager = strapiClient.single(contentType)
return await manager.find(queryParams, { headers, ...otherOptions })
} else {
const manager = strapiClient.collection(contentType)
return await manager.find(queryParams, { headers, ...otherOptions })
}
} catch (error) {
console.error(`Error fetching ${contentType}:`, error)
throw error
}
}
/**
* Fetch global content with preview support
*/
export const getGlobal = async (previewOptions = {}) => {
return await fetchWithPreview('global', {
isSingle: true,
...previewOptions,
})
}
/**
* Fetch a collection item by slug with preview support
*/
export const getBySlug = async (contentType, slug, previewOptions = {}) => {
return await fetchWithPreview(contentType, {
isSingle: false,
params: {
filters: { slug: { $eq: slug } },
populate: '*',
},
...previewOptions,
})
}
/**
* Fetch a single item by document ID (useful for preview)
*/
export const getByDocumentId = async (
contentType,
documentId,
previewOptions = {},
) => {
const { isSingle = false } = previewOptions
if (isSingle) {
return await fetchWithPreview(contentType, {
isSingle: true,
params: { documentId },
...previewOptions,
})
} else {
return await fetchWithPreview(contentType, {
isSingle: false,
params: {
filters: { documentId: { $eq: documentId } },
populate: '*',
},
...previewOptions,
})
}
}