From 7e777bbb56f9d4b0cc759c616cb3460b56341b1f Mon Sep 17 00:00:00 2001 From: DIYgod Date: Fri, 25 Sep 2020 12:01:01 +0800 Subject: [PATCH] feat: youtube key retry --- lib/routes/youtube/utils.js | 73 ++++++++++++++++++++++++------------- 1 file changed, 47 insertions(+), 26 deletions(-) diff --git a/lib/routes/youtube/utils.js b/lib/routes/youtube/utils.js index c796ae8c7..e1bfe5b46 100644 --- a/lib/routes/youtube/utils.js +++ b/lib/routes/youtube/utils.js @@ -1,12 +1,10 @@ const { google } = require('googleapis'); const config = require('@/config').value; -let getYoutube = () => null; +let count = 0; +const youtube = {}; if (config.youtube.key) { const keys = config.youtube.key.split(','); - const youtube = {}; - let count = 0; - let index = -1; keys.forEach((key, index) => { if (key) { @@ -17,44 +15,67 @@ if (config.youtube.key) { count = index + 1; } }); - - getYoutube = () => { - index++; - return youtube[index % count]; - }; } +let index = -1; +const exec = async (func) => { + let result; + for (let i = 0; i < count; i++) { + index++; + try { + // eslint-disable-next-line no-await-in-loop + result = await func(youtube[index % count]); + break; + } catch (error) { + // console.error(error); + } + } + return result; +}; + const youtubeUtils = { getPlaylistItems: async (id, part) => { - const res = await getYoutube().playlistItems.list({ - part, - playlistId: id, - maxResults: 50, // youtube api param value default is 5 - }); + const res = await exec( + async (youtube) => + await youtube.playlistItems.list({ + part, + playlistId: id, + maxResults: 50, // youtube api param value default is 5 + }) + ); return res; }, getPlaylist: async (id, part, cache) => await cache.tryGet('getPlaylist' + id, async () => { - const res = await getYoutube().playlists.list({ - part, - id: id, - }); + const res = await exec( + async (youtube) => + await youtube.playlists.list({ + part, + id: id, + }) + ); return res; }), getChannelWithId: async (id, part, cache) => await cache.tryGet('getChannelWithId' + id, async () => { - const res = await getYoutube().channels.list({ - part, - id: id, - }); + const res = await exec( + async (youtube) => + await youtube.channels.list({ + part, + id: id, + }) + ); return res; }), getChannelWithUsername: async (username, part, cache) => await cache.tryGet('getPlaylist' + username, async () => { - const res = await getYoutube().channels.list({ - part, - forUsername: username, - }); + const res = await exec( + async (youtube) => + await youtube.channels.list({ + part, + forUsername: username, + }) + ); return res; }), getThumbnail: (thumbnails) => thumbnails.maxres || thumbnails.standard || thumbnails.high || thumbnails.medium || thumbnails.default,