| 1 |
import { AI_HOST } from '@constants'; |
| 2 |
import { useAIConsentStore } from '@shared/state/ai-consent'; |
| 3 |
import { useUnsplashCacheStore } from '@shared/state/unsplash-cache'; |
| 4 |
|
| 5 |
const { showAIConsent, userGaveConsent } = useAIConsentStore.getState(); |
| 6 |
|
| 7 |
// Additional data to send with requests |
| 8 |
const allowList = [ |
| 9 |
'siteId', |
| 10 |
'partnerId', |
| 11 |
'wpVersion', |
| 12 |
'wpLanguage', |
| 13 |
'devbuild', |
| 14 |
'isBlockTheme', |
| 15 |
'userId', |
| 16 |
'siteProfile', |
| 17 |
]; |
| 18 |
|
| 19 |
const extraBody = { |
| 20 |
...Object.fromEntries( |
| 21 |
Object.entries(window.extSharedData).filter(([key]) => |
| 22 |
allowList.includes(key), |
| 23 |
), |
| 24 |
), |
| 25 |
showAIConsent, |
| 26 |
userGaveConsent, |
| 27 |
}; |
| 28 |
|
| 29 |
export const fetchImages = async (search, source = null) => { |
| 30 |
const queryString = new URLSearchParams({ |
| 31 |
...extraBody, |
| 32 |
query: search, |
| 33 |
source, |
| 34 |
}); |
| 35 |
|
| 36 |
const res = await fetch( |
| 37 |
`${AI_HOST}/api/draft/image/unsplash?${queryString.toString()}`, |
| 38 |
{ |
| 39 |
method: 'GET', |
| 40 |
headers: { 'Content-Type': 'application/json' }, |
| 41 |
}, |
| 42 |
); |
| 43 |
|
| 44 |
if (!res.ok) { |
| 45 |
throw new Error('Bad response from server'); |
| 46 |
} |
| 47 |
|
| 48 |
const images = await res.json(); |
| 49 |
|
| 50 |
if (!Array.isArray(images)) { |
| 51 |
throw new Error('Bad response from server'); |
| 52 |
} |
| 53 |
|
| 54 |
const result = images.map((image) => ({ |
| 55 |
...image, |
| 56 |
requestMetadata: { |
| 57 |
id: res.headers.get('X-Request-Id'), |
| 58 |
total: res.headers.get('X-Total'), |
| 59 |
perPage: res.headers.get('X-Per-Page'), |
| 60 |
}, |
| 61 |
})); |
| 62 |
|
| 63 |
return result; |
| 64 |
}; |
| 65 |
|
| 66 |
export const preFetchImages = async () => { |
| 67 |
const cache = useUnsplashCacheStore.getState(); |
| 68 |
if (!cache.isEmpty() && !cache.hasExpired()) { |
| 69 |
return cache.images; |
| 70 |
} |
| 71 |
|
| 72 |
const { aiKeywords } = window.extSharedData?.siteProfile ?? {}; |
| 73 |
const queries = aiKeywords?.length ? aiKeywords : []; |
| 74 |
const images = ( |
| 75 |
await Promise.all(queries.map((query) => fetchImages(query, 'prefetch'))) |
| 76 |
).flat(); |
| 77 |
|
| 78 |
const uniqueImagesMap = images.reduce((acc, image) => { |
| 79 |
if (!acc.has(image.id)) { |
| 80 |
acc.set(image.id, image); |
| 81 |
} |
| 82 |
return acc; |
| 83 |
}, new Map()); |
| 84 |
cache.updateCache(Array.from(uniqueImagesMap.values())); |
| 85 |
|
| 86 |
return images; |
| 87 |
}; |
| 88 |
|