Обратный звонок Google Диска не работает в Express обратных вызовах - PullRequest
1 голос
/ 14 января 2020

Я занимаюсь разработкой веб-приложения для системы инвентаризации. Я хочу отобразить изображения инвентаря на основе ручек. Изображения находятся в Google Drive, мне нужно отображать изображения на основе папки. Я скопировал код диска Node.Js, но не могу получить значения вне функции. Пожалуйста, помогите мне завершить код.

Здесь код диска Google:

function gettingDriveimages(handleID)
{
  fs.readFile('./public/api/google/credentials.json', (err, content) => {
    if (err) return console.log('Error loading client secret file:', err);
    console.log (handleID);
    var gDrive = authorize(JSON.parse(content), handleID, listFiles);
    console.log(gDrive);
   });
}

function authorize(credentials, handleID, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, handleID, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    return callback(oAuth2Client, handleID);
  });
}

function getAccessToken(oAuth2Client, handleID, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
  rl.close();
  oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
        oAuth2Client.setCredentials(token);
        // Store the token to disk for later program executions
        fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
      if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client, handleID);
  });
  });
}

function listFiles(auth, handleID) {
//console.log(handleID);
  var classifData2 = [];
  const drive = google.drive({version: 'v3', auth});
  const googleFolder = '1hiqS_xXSWyqZXU3SkXJYq4COJFa--1pm';
  drive.files.list({
  fields: 'nextPageToken, files(id, name, mimeType)',
  q: `'${googleFolder}' in parents`
  }, (err, res) => {
  if (err) return console.log('The API returned an error: ' + err);
  const files = res.data.files;
  const mimeType = 'application/vnd.google-apps.folder';
  const foldername = handleID;

  if (files.length) {
      files.map((file) => {
      if ((file.name == foldername) && (file.mimeType == mimeType))
      {
          //console.log(file.id);
          drive.files.list({
          fields: 'nextPageToken, files(id, name, mimeType, webViewLink)',
          q: `'${file.id}' in parents`,
          }, (err, res) => {
          if (err) return console.log('The API returned an error: ' + err);
          const images = res.data.files;
          const imageMime1 = 'image/jpeg';
          const imageMime2 = 'image/png';
          if (images.length) {
              images.map((image) => {
              if ((image.mimeType == imageMime1) || (image.mimeType == imageMime2))
              {
                  classifData2 = classifData2.concat({
                  imagename : image.name,
                  imageid : image.id,
                  });
              }
              });
          }
          //console.log (classifData2);
          return classifData2;
          });               
      } 
      });
  }
  });
}  

Здесь express обратный вызов

router.get('/handletaken/:id', async(req, res) => {
    var handleID = req.params.id;
    var classifData1 = gettingDriveimages(handleID);
    console.log(classifData1);
    res.send(classifData1)
});
...