Issue with proGallery.update

Question:
I really don’t understand what can cause the issue and why gallery is not updating with new items.
I am getting console error: System error occurred, request-id: 1716075306.126488292727110979" And gallery is not being updated

Product:
Wix EDITOR

What are you trying to achieve:
Updating the gallery with new files(images)

Additional information:
Current frontend code:

if ($w("#uploadPhotos").value.length > 0) {
                $w("#infoText").hide();
                const uploadedFiles = await $w("#uploadPhotos").uploadFiles();
                const inspectionItem = await getInspectionByOrderId(orderId);
                await storeInspectionPhotos(inspectionItem._id, uploadedFiles);

                const galleryItem = await getGalleryByInspectionId(inspectionItem._id); // Ensure this retrieves the correct gallery item
                const galleryDetails = await getGalleryDetails(galleryItem.galleryId);

                const newItems = uploadedFiles.map(file => ({
                    title: file.originalFileName,
                    description: "",
                    src: file.fileUrl,
                    settings: {
                        focalPoint: [0.5, 0.5]
                    }
                }));

                console.log("New items to add:", newItems);

                const updatedGallery = await updateGallery(galleryItem.galleryId, newItems, "Updated Gallery");

                $w("#gallery1").items = updatedGallery.items.map(item => ({
                    type: "image",
                    src: item.image.imageInfo
                }));

                $w("#infoText").text = "Images uploaded and gallery updated!";
                $w("#uploadPhotos").reset();

Backend code:

import wixData from 'wix-data';

import { proGallery } from 'wix-pro-gallery-backend';

import { elevate } from 'wix-auth';

import wixUsers from 'wix-users-backend';

export async function updateGallery(galleryId, items, name) {
    try {
        if (!galleryId) {
            throw new Error("Invalid gallery ID: " + galleryId);
        }
        console.log("Updating gallery with ID:", galleryId);
        console.log("Items:", items);

        if (!Array.isArray(items)) {
            throw new Error("Items parameter is not an array");
        }

        const formattedItems = items.map(item => {
            if (!item.src) {
                throw new Error(`Invalid image source: ${item.src}`);
            }

            return {
                title: item.title || "",
                description: item.description || "",
                image: {
                    imageInfo: item.src
                },
                settings: {
                    focalPoint: [0.5, 0.5]
                }
            };
        });

        const updateOptions = {
            name: name,
            items: formattedItems
        };

        const elevatedUpdateGallery = elevate(proGallery.updateGallery);
        const updatedGallery = await elevatedUpdateGallery(galleryId, updateOptions);

        console.log("Updated gallery:", updatedGallery);
        return updatedGallery;
    } catch (error) {
        console.error("Error updating gallery:", error.message);
        throw error;
    }
}

Could anyone try to look where is the issue here? I have a felling that i have wrong formatting.

I also checked console how the file src is presented, all looks ok. When creating gallery - i have no issues.

Thanks for help!

@anon72313111

Can you give an example of the items that are failing to be updated in the gallery? (ie. what does updateOptions look like?)

Thanks for responding. I actually found issue. I was always using updateGallery() rather than updateGalleryItem()… :cold_face: :grinning:

Anyway if someone ever needs guidance, i am attaching code samples how to correctly handle PRO Gallery API (Backend) should look like. I personally have not found any support regarding this case in forums, only API.

We are refering to: import { proGallery } from ‘wix-pro-gallery-backend’;

API LINK

Example case to add Gallery Items into the existing gallery(frontend):

$w('#uploadMoreButton').onClick(async () => {
        const files = $w('#uploadPhotos').value;
        if (files.length === 0) {
            $w('#infoText').text = 'Please select new files to upload';
            return;
        }

        $w('#uploadMoreButton').hide();
        $w('#GIFupload').show();

        try {
            const uploadedFiles = await $w('#uploadPhotos').uploadFiles();
            const successfulUploads = uploadedFiles.filter(file => file.fileUrl);

            if (successfulUploads.length === 0) {
                $w('#infoText').text = 'Error uploading files.';
                return;
            }

            const results = await createGalleryItems(currentGalleryId, successfulUploads);
            if (results.success) {
                $w('#infoText').text = 'Upload successful!';
                const { items, totalItems } = await getGalleryItems(currentGalleryId, ITEMS_PER_PAGE, 0);
                currentGalleryItemsTotal = totalItems;
                $w('#galleryItemsRepeater').data = items;
                setupPagination(currentGalleryItemsTotal, ITEMS_PER_PAGE, 1, '#pagination1');
            } else {
                $w('#infoText').text = 'Error uploading files: ' + results.error;
            }
        } catch (error) {
                    $w('#infoText').text = 'Error uploading files: ' + error.message;
        } finally {
            $w('#GIFupload').hide();
            $w('#uploadMoreButton').show();
        }
    });

Backend handling and inserting new items into PRO Gallery:

import { elevate } from 'wix-auth';
import { proGallery } from 'wix-pro-gallery-backend';
import { mediaManager } from 'wix-media-backend';
import { Permissions, webMethod } from 'wix-web-module';
import wixData from 'wix-data';

export async function createGalleryItems(galleryId, files) {
    return webMethod(Permissions.Anyone, async () => {
        try {
            const elevatedCreateGalleryItem = elevate(proGallery.createGalleryItem);

            const createdItems = await Promise.all(files.map(async file => {
                const item = {
                    title: file.originalFileName,
                    image: {
                        type: "WIX_MEDIA", 
                        imageInfo: file.fileUrl
                    }
                };
                return await elevatedCreateGalleryItem(galleryId, item);
            }));

            return { success: true, items: createdItems };
        } catch (error) {
            console.error('Error creating gallery items:', error);
            return { success: false, error };
        }
    })();
}

Additional (backend) cases for getting gallery or items, deleting items, deleting gallery, updating gallery:

Get all galleries:

export async function getGalleries(offset = 0, limit = 10) {
    try {
        const elevatedListGalleries = elevate(proGallery.listGalleries);
        const result = await elevatedListGalleries({ offset, limit });
        return {
            galleries: result.galleries,
            totalGalleries: result.totalGalleries,
        };
    } catch (error) {
        console.error('Error fetching galleries:', error);
        throw error;
    }
}

Delete gallery item:

export async function deleteGalleryItem(galleryId, itemId) {
    return webMethod(Permissions.Anyone, async () => {
        try {
            const elevatedDeleteGalleryItem = elevate(proGallery.deleteGalleryItem);
            const deletedGalleryItemId = await elevatedDeleteGalleryItem({ galleryId, itemId });
            return { success: true, itemId: deletedGalleryItemId };
        } catch (error) {
            console.error('Error deleting gallery item:', error);
            return { success: false, error };
        }
    })();
}

Get gallery items:

export async function getGalleryItems(galleryId, itemLimit, itemOffset) {
    return webMethod(Permissions.Anyone, async () => {
        try {
            const result = await proGallery.listGalleryItems(galleryId, { itemLimit, itemOffset });
            let totalItems = 0;

            // Get total items by fetching in batches of 100 until we get all items
            let fetchedItems = [];
            let offset = 0;
            const limit = 100;
            let fetchMore = true;

            while (fetchMore) {
                const response = await proGallery.listGalleryItems(galleryId, { itemLimit: limit, itemOffset: offset });
                fetchedItems = fetchedItems.concat(response.items);
                offset += limit;
                if (response.items.length < limit) {
                    fetchMore = false;
                }
            }

            totalItems = fetchedItems.length;

            return { items: result.items, totalItems };
        } catch (error) {
            console.error('Error fetching gallery items:', error);
            throw error;
        }
    })();
}

Update gallery name:

export async function updateGalleryName(galleryId, newName) {
    return webMethod(Permissions.Anyone, async () => {
        try {
            const elevatedUpdateGallery = elevate(proGallery.updateGallery);
            const updatedGallery = await elevatedUpdateGallery(galleryId, { name: newName });
            return { success: true, updatedGallery };
        } catch (error) {
            console.error('Error updating gallery name:', error);
            return { success: false, error };
        }
    })();
}

Mapping PRO Gallery element in frontend:

const galleryDetails = await getGalleryDetails(galleryItem.galleryId);
$w("#gallery1").items = galleryDetails.items.map(item => ({
                type: "image",
                src: item.image.imageInfo
            }));

Hopefully this helps to someone who is struggling to understand how PRO galleries works in the backend. :metal:

2 Likes

Thanks for sharing such a detailed solution!