2017-04-18 6 views
1

Axe를 사용하여 Deezer API에 요청합니다. 불행하게도 Deezer의 API를 사용하면 아티스트의 앨범을 요청할 때 앨범 트랙이 포함되지 않습니다. 그래서 저는이 문제를 해결하기 위해 아티스트의 앨범을 요청한 다음 각 앨범에 대한 액시스 요청을 수행합니다. 내가 겪고있는 문제는 API가 요청을 5 초당 50 개로 제한한다는 것입니다. 아티스트의 앨범 수가 50 개가 넘으면 보통 "할당량 초과"오류가 발생합니다. 액시스 요청을 5 초당 50 회까지 조절할 수있는 방법이 있습니까? 특히 axios.all을 사용할 때 그렇습니다. 모든Axios 요청 조절

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을 사용하는 것과 다를 바없이 모든 요청이 완료되기를 기다리고 싶을뿐입니다.)

액시스를 사용하면 요청 전에 논리를 연결할 수있는 차단 API가 있습니다. 그래서이 같은 인터셉터를 사용할 수 있습니다

그것은 그들이 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보다 적은 요청의 수를 가능한 한 빨리 결과를 받고 싶습니다되고, 당신은 요청의 수를 세고 인터벌과 카운터 모두에 기반하여 그들의 실행을 지연시킬 스케줄러 안에 어떤 종류의 카운터를 추가해야한다.