CCCPaste

1d2e2e9622f93

(async () => {

const apolloClient = (() => {
    const entry = document.querySelector('[data-testid^="entry-"]');
    const fk = Object.keys(entry).find(k => k.startsWith('__reactFiber'));
    let n = entry[fk];
    while (n) {
        const ctx = n.memoizedProps?.value?.client ?? n.memoizedProps?.client;
        if (ctx?.cache) return ctx;
        n = n.return;
    }
})();

const csrfToken = document.cookie.match(/csrf-token=([^;]+)/)?.[1] ?? '';
const fetchEntries = (from, limit) => fetch('/titanarum/public', {
    method: 'POST',
    headers: { 'content-type': 'application/json', 'x-csrf-token': csrfToken },
    body: JSON.stringify({
        operationName: 'Votes',
        variables: { slug: 'mediterranean-hues-2026-03', limit, from },
        query: `query Votes($slug: String!, $from: Int, $limit: Int) {
            challengeEntriesForVoting(slug: $slug, from: $from, limit: $limit) {
                results {
                    entries {
                        id designId challengeId entryImage entryPlace validVotes
                        isFavorite isSelected entryTitle entryDescription
                        entryStatus entryState pdpUrl product
                        image { L M S XS __typename }
                        user { userId userName userImage __typename }
                        __typename
                    }
                    __typename
                }
                __typename
            }
        }`
    })
}).then(r => r.json());

const [res1, res2] = await Promise.all([fetchEntries(0, 1000), fetchEntries(1000, 1000)]);
const allEntries = [
    ...res1.data.challengeEntriesForVoting.results.entries,
    ...res2.data.challengeEntriesForVoting.results.entries
];
console.log(`✅ ${allEntries.length} entry`);

// Scrivi tutte le entry mancanti nella cache come oggetti normalizzati
const cacheSnapshot = apolloClient.cache.extract();
const toWrite = {};

allEntries.forEach(e => {
    // BaseUser
    const userKey = `BaseUser:{"userId":"${e.user.userId}"}`;
    if (!cacheSnapshot[userKey]) {
        toWrite[userKey] = {
            __typename: 'BaseUser',
            userId: e.user.userId,
            userName: e.user.userName,
            userImage: e.user.userImage
        };
    }
    // Entry
    const entryKey = `ChallengeEntryWithUserValues:${e.id}`;
    if (!cacheSnapshot[entryKey]) {
        toWrite[entryKey] = {
            __typename: 'ChallengeEntryWithUserValues',
            id: e.id, designId: e.designId, challengeId: e.challengeId,
            entryImage: e.entryImage, entryPlace: e.entryPlace, validVotes: e.validVotes,
            isFavorite: e.isFavorite, isSelected: e.isSelected, entryTitle: e.entryTitle,
            entryDescription: e.entryDescription, entryStatus: e.entryStatus,
            entryState: e.entryState, pdpUrl: e.pdpUrl, product: e.product,
            image: { __typename: 'DesignImage', L: e.image.L, M: e.image.M, S: e.image.S, XS: e.image.XS },
            user: { __ref: userKey }
        };
    }
});

// Costruisci il nuovo ROOT_QUERY con le entry aggiornate
const allRefs = allEntries.map(e => ({ __ref: `ChallengeEntryWithUserValues:${e.id}` }));
const existingRoot = cacheSnapshot['ROOT_QUERY'];
const buildEntry = (fromVal) => ({
    __typename: 'ChallengeEntriesForVoting',
    info: {
        __typename: 'ChallengeEntriesVotingInfo',
        pagination: { __typename: 'Pagination', limit: allEntries.length, offset: 0, total: 1735 },
        votingStats: { __ref: 'VotingStats:{}' }
    },
    results: {
        __typename: 'ChallengeEntriesForVotingResults',
        entries: allRefs,
        promotedEntry: null,
        guestVoting: null
    }
});

toWrite['ROOT_QUERY'] = {
    ...existingRoot,
    'challengeEntriesForVoting({"from":null,"limit":84,"slug":"mediterranean-hues-2026-03"})': buildEntry(null),
    'challengeEntriesForVoting({"from":0,"limit":84,"slug":"mediterranean-hues-2026-03"})': buildEntry(0),
};

// Restore diretto nella cache interna
apolloClient.cache.restore({ ...cacheSnapshot, ...toWrite });
apolloClient.cache.broadcastWatches();

console.log(`🎨 Cache ripristinata con ${allEntries.length} entry su entrambe le chiavi!`);
})();