๐Ÿชด React

[React/ํŒ€ํ”„์ ] Youtube API ์‚ฌ์šฉํ•˜๊ธฐ

๋ จ๋”” 2024. 2. 26. 23:09
SMALL

 

 

์ด๋Ÿฐ ์‹์œผ๋กœ api ๋ฅผ ์“ฐ๋Š”๊ฒŒ ๋งž๋Š” ์ง€ ๋ชจ๋ฅด๊ฒ ์œผ๋‚˜..

์•„๋งˆ api - axios.get  ์ œ์™ธํ•œ ๋ถ€๋ถ„์€ ๋”ฐ๋กœ ๋นผ๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™๊ธด ํ•˜๋‹ค.

 

...api.js

import axios from 'axios';
import request from './request';
// ๋ฉ”์ธํŽ˜์ด์ง€ BodySlider - ์œ ํŠœ๋ฒ„ ์˜์ƒ ์Šฌ๋ผ์ด๋”์— ์‚ฌ์šฉ๋  youtube data api

export const mainSliderDataClient = axios.create({
  baseURL: import.meta.env.VITE_APP_YOUTUBE_BASE_URL_GET,
  headers: {
    'Content-Type': 'application/json'
  },
  responseType: 'json'
});

// input: ์˜์ƒid   output: ์˜์ƒ์ธ๋„ค์ผ์ด๋ฏธ์ง€url ๋ฐ ํ•ด๋‹น ์ฑ„๋„ ์ •๋ณด๊ฐ€ ๋‹ด๊ธด ๊ฐ์ฒด
export const getVideoChannelDatabyId = async (videoId) => {
  // ์˜์ƒid ํ•œ๋ฒˆ๋งŒ ๋ฐ›์•„์„œ ์ฑ„๋„id๊นŒ์ง€ ์ฐพ์„ ์ˆ˜ ์žˆ์œผ๋‹ˆ ํ•œ๋ฒˆ์— ์ฑ„๋„id๋กœ ์—ฐ๊ฒฐ์‹œ์ผœ์„œ ์ฑ„๋„idํ†ตํ•ด ์œ ํŠœ๋ฒ„(์ฑ„๋„)๋ช…, ๊ตฌ๋…์ž์ˆ˜ ๋“ฑ ๊ฐ์ฒด๋กœ ์ „๋‹ฌํ•ด์ฃผ๊ธฐ
  try {
    const videoResponse = await mainSliderDataClient.get(`${request.getVideoSnippet}&id=${videoId}`);
    // console.log(videoResponse.data);
    const snippet = videoResponse.data.items[0].snippet;
    const channelId = snippet.channelId; // ์˜์ƒ idํ†ตํ•ด ์ฑ„๋„ id ์–ป๊ธฐ
    const channelTitle = snippet.channelTitle; // ์ฑ„๋„๋ช… (์œ ํŠœ๋ฒ„๋ช…)
    const thumbnailUrl = snippet.thumbnails.standard.url; // ์˜์ƒ ์ธ๋„ค์ผ์ด๋ฏธ์ง€ url

    // ์œ„์˜ ๋ฐ›์€ ์ฑ„๋„ id ์‚ฌ์šฉ
    const channelResponse = await mainSliderDataClient.get(`${request.getChannelStatistics}&id=${channelId}`);
    // console.log(channelResponse.data);

    const statistics = channelResponse.data.items[0].statistics;
    const initSubscriberCount = statistics.subscriberCount; // ์ฑ„๋„ ๊ตฌ๋…์ž์ˆ˜
    const videoCount = statistics.videoCount; // ์ฑ„๋„ ์ด ์˜์ƒ์ˆ˜
    const viewCount = statistics.viewCount; // ์ฑ„๋„ ์ด ์กฐํšŒ์ˆ˜(๋ชจ๋“  ์˜์ƒ ์กฐํšŒ์ˆ˜์˜ ํ•ฉ)
    const initAverageViewCount = viewCount / videoCount; // (์ผ๋ฐ˜์ ์ธ) ์ฑ„๋„ ํ‰๊ท  ์กฐํšŒ์ˆ˜ (์ด ์กฐํšŒ์ˆ˜ / ์ด ์˜์ƒ ์ˆ˜)

    const subscriberCount =
      initSubscriberCount > 10000
        ? Math.round(initSubscriberCount / 10000) + '๋งŒ'
        : Math.round((initSubscriberCount / 1000) * 10) / 10 + '์ฒœ';
    const averageViewCount =
      initAverageViewCount > 10000
        ? Math.round(initAverageViewCount / 10000) + '๋งŒ'
        : Math.round((initAverageViewCount / 1000) * 10) / 10 + '์ฒœ';

    return { channelTitle, thumbnailUrl, subscriberCount, averageViewCount };
    // ์ฑ„๋„๋ช…(์œ ํŠœ๋ฒ„๋ช…), ์˜์ƒ์ธ๋„ค์ผ์ด๋ฏธ์ง€url, ์ฑ„๋„๊ตฌ๋…์ž์ˆ˜(๋งŒ ๋‹จ์œ„), ์ฑ„๋„ํ‰๊ท ์กฐํšŒ์ˆ˜(๋งŒ ๋‹จ์œ„)
  } catch (error) {
    console.error('failed to get data by function getVideoChannelDatabyId', error.message);
  }
};
SMALL