Skip to content

Commit

Permalink
Youtube: Cache requested video data
Browse files Browse the repository at this point in the history
  • Loading branch information
mia-pi-git committed Oct 27, 2020
1 parent bdad542 commit 7830f42
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions server/chat-plugins/youtube.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {Utils} from '../../lib/utils';
const ROOT = 'https://www.googleapis.com/youtube/v3/';
const STORAGE_PATH = 'config/chat-plugins/youtube.json';

export const videoDataCache: Map<string, VideoData> = Chat.oldPlugins.youtube?.videoDataCache || new Map();

interface ChannelEntry {
name: string;
description: string;
Expand Down Expand Up @@ -148,13 +150,20 @@ export class YoutubeInterface {
return Promise.resolve({...this.data.channels[id]});
}
async getVideoData(id: string): Promise<VideoData | null> {
const raw = await Net(`${ROOT}videos`).get({
query: {part: 'snippet,statistics', id, key: Config.youtubeKey},
});
const cached = videoDataCache.get(id);
if (cached) return Promise.resolve(cached);
let raw;
try {
raw = await Net(`${ROOT}videos`).get({
query: {part: 'snippet,statistics', id, key: Config.youtubeKey},
});
} catch (e) {
throw new Chat.ErrorMessage(`Failed to retrieve video data: ${e.message}.`);
}
const res = JSON.parse(raw);
if (!res || !res.items || res.items.length < 1) return null;
const video = res.items[0];
return {
const data: VideoData = {
title: video.snippet.title,
id,
date: new Date(video.snippet.publishedAt).toString(),
Expand All @@ -166,6 +175,8 @@ export class YoutubeInterface {
likes: video.statistics.likeCount,
dislikes: video.statistics.dislikeCount,
};
videoDataCache.set(id, data);
return Promise.resolve(data);
}
channelSearch(search: string) {
let channel;
Expand Down

0 comments on commit 7830f42

Please sign in to comment.