2017-04-18 9 views
1

Axeを使用してDeezer APIにリクエストしています。残念なことに、DeezerのAPIを使用してアーティストのアルバムをリクエストすると、アルバムトラックは含まれません。だから、私はアーティストのアルバムを要求し、その後、それぞれのアルバムに対して次のアキシオのリクエストを行うことでこれを回避しようとしています。私が取り組んでいる問題は、APIが要求を5秒あたり50に制限していることです。アーティストが50以上のアルバムを持っている場合は、通常、「クォータを超過しました」というエラーが表示されます。 Axios.allを使用しているときに、5秒ごとに50までのAxiosリクエストを調整する方法はありますか?Axioリクエストを調整する

var axios = require('axios'); 

function getAlbums(artistID) { 
    axios.get(`https://api.deezer.com/artist/${artistID}/albums`) 
    .then((albums) => { 
     const urls = albums.data.data.map((album) => { 
     return axios.get(`https://api.deezer.com/album/${album.id}`) 
      .then(albumInfo => albumInfo.data); 
     }); 
     axios.all(urls) 
     .then((allAlbums) => { 
      console.log(allAlbums); 
     }); 
    }).catch((err) => { 
     console.log(err); 
    }); 
} 

getAlbums(413); 

答えて

1

すべての最初に、あなたが本当に必要性を見てみましょう。ここでの目標は、多数のアルバムがある場合は、最大100ミリ秒ごとにリクエストすることです。 (axios.allを使用しても、Promise.allを使用するのと同じですが、すべての要求が完了するのを待つだけです)。

ここで、Axiosを使用すると、要求の前にロジックをプラグインすることができます。ですから、このようなインターセプターを使用することができます。

それは彼らが intervalMsミリ秒間隔で実行されるように要求するタイミングである何
function scheduleRequests(axiosInstance, intervalMs) { 
    let lastInvocationTime = undefined; 

    const scheduler = (config) => { 
     const now = Date.now(); 
     if (lastInvocationTime) { 
      lastInvocationTime += intervalMs; 
      const waitPeriodForThisRequest = lastInvocationTime - now; 
      if (waitPeriodForThisRequest > 0) { 
       return new Promise((resolve) => { 
        setTimeout(
         () => resolve(config), 
         waitPeriodForThisRequest); 
       }); 
      } 
     } 

     lastInvocationTime = now; 
     return config; 
    } 

    axiosInstance.interceptors.request.use(scheduler); 
} 

。あなたのコードで

function getAlbums(artistID) { 
    const deezerService = axios.create({ baseURL: 'https://api.deezer.com' }); 
    scheduleRequests(deezerService, 100); 

    deezerService.get(`/artist/${artistID}/albums`) 
     .then((albums) => { 
      const urlRequests = albums.data.data.map(
        (album) => deezerService 
         .get(`/album/${album.id}`) 
         .then(albumInfo => albumInfo.data)); 

      //you need to 'return' here, otherwise any error in album 
      // requests will not propagate to the final 'catch': 
      return axios.all(urls).then(console.log); 
     }) 
     .catch(console.log); 
} 

これは、あなたのケースであなたはおそらく少ない。このために50以上の要求の数のために、できるだけ速く結果を受け取りたい、しかし、単純なアプローチでありますスケジューラー内に何らかの種類のカウンターを追加する必要があります。このカウンターは要求の数をカウントし、間隔とカウンターの両方に基づいて実行を延期します。