comedian.ts

import { CHANNEL_IDS, VIDEOS } from '../../utility/constants/values';

async function getComedianData(context, category, comedianId) {
  const { firestore, envmt, activeDbId } = context;
  const snapshot = await firestore
    .collection(`${envmt}-${category}-${activeDbId}`)
    .where('comedianId', '==', comedianId)
    .get();

  let comedian;

  snapshot.forEach((document) => {
    const data = { ...document.data() };
    const { comedianId = '', snippet = {} } = data;
    comedian = {
      id: comedianId,
      name: snippet.title,
      photoURL: snippet?.thumbnails?.medium?.url
    };
  });

  return comedian;
}

async function getComedianVideos(context, category, comedianId) {
  const { firestore, envmt, activeDbId } = context;
  const snapshot = await firestore
    // TODO update the name to be dynamic based on environment and active shard
    .collection(`${envmt}-${category}-${activeDbId}`)
    .where('comedianId', '==', comedianId)
    .orderBy('statistics.viewCount', 'desc')
    .limit(50)
    .get();

  let videos = [];
  snapshot.forEach((doc) => {
    videos.push(doc.data());
  });

  return videos;
}

export async function getComedian(context, comedianId: String) {
  const [basic, videos] = await Promise.all([
    getComedianData(context, CHANNEL_IDS, comedianId),
    getComedianVideos(context, VIDEOS, comedianId)
  ]);
  return {
    basic,
    videos
  };
}