function cachePreviewResults(results, formatIds, manifests) {
results.forEach((result, idx) => {
if (result.success) {
const cacheKey = `${formatIds[idx]}:${hashManifest(manifests[idx])}`;
cache.set(cacheKey, result.response, result.response.expires_at);
}
});
}
async function getPreviewsWithCache(formatIds, manifests) {
const cached = [];
const toFetch = [];
formatIds.forEach((id, idx) => {
const cacheKey = `${id}:${hashManifest(manifests[idx])}`;
const cachedResult = cache.get(cacheKey);
if (cachedResult && !isExpired(cachedResult.expires_at)) {
cached[idx] = cachedResult;
} else {
toFetch.push({ idx, id, manifest: manifests[idx] });
}
});
// Batch fetch only missing previews
if (toFetch.length > 0) {
const fetched = await client.preview_creative({
request_type: "batch",
output_format: "html",
requests: toFetch.map(f => ({
format_id: f.id,
creative_manifest: f.manifest
}))
});
fetched.results.forEach((result, i) => {
cached[toFetch[i].idx] = result.response;
});
}
return cached;
}