javascriptnode.jsgoogle-drive-apiservice-accountsgoogle-api-nodejs-client

Live display new added photos from google drive api


Using Google drive Api and a service account I get photos from google drive, all the photos that were originally on the drive are displayed correctly, but if I add a new photo to google drive, the photo itself is not displayed, only its name

const { google } = require('googleapis');
const path = require('path');

const getDriveService = () => {
  const KEYFILEPATH = path.join(__dirname, 'settings.json');
  const SCOPES = ['https://www.googleapis.com/auth/drive'];

  const auth = new google.auth.GoogleAuth({
    keyFile: KEYFILEPATH,
    scopes: SCOPES,
  });
  const driveService = google.drive({ version: 'v3', auth });
  return driveService;
};


function getThumbnailUrl(fileId) {
  const timestamp = Date.now(); // Cache-busting parameter
  return `https://drive.google.com/thumbnail?id=${fileId}&timestamp=${timestamp}`;
}
export function getPhotosFromDrive() {
  const driveService = getDriveService();

  return driveService.files.list({
    q: "mimeType='image/jpeg' or mimeType='image/png'", // Filter for JPEG and PNG images
    fields: 'files(id, name, webViewLink)', // Specify the fields to retrieve
  })
    .then(response => {
      const photos = response.data.files;
      return photos.map(photo => ({
        name: photo.name,
        id: photo.id,
        webViewLink: getThumbnailUrl(photo.id)
      }));
    })
    .catch(error => {
      console.error('Error retrieving photos:', error);
      throw error;
    });
}
import { getPhotosFromDrive } from 'backend/photosGallery';

$w.onReady(function () {
  getPhotosFromDrive()
    .then(photos => {
      const galleryItems = photos.map(photo => ({
        type: 'image',
        src: photo.webViewLink,
        title: photo.name
      }));

      $w('#gallery1').items = galleryItems;
    })
    .catch(error => {
      console.error('Error retrieving photos:', error);
      // Handle the error
    });
});

enter image description here


Solution

  • Suggestion

    Since I do not have the complete details of your setup, I can only make guesses to help with the investigation. You can use this as a starting point for further troubleshooting.

    Based on my own testing:

    Reference