home.ts

import * as path from 'path';
import * as fs from 'fs';
import * as util from 'util';
import { DEV, DOMAIN_NAME_PPP, DOMAIN_NAME_PROD, PROD } from '../config/constants';
import { getComedian } from '../endpoints/fetch/comedians';

function getPageId(urlPath) {
  const route = urlPath.split('/');
  if (route[1] === 'comedians' && route[2] !== '') return ['comedian', route[2]];
  if (route[1] === 'comedians') return ['comedians'];
  if (route[1] === 'search') return ['search'];
  return ['home'];
}

function updateMetaTags(content, title, description, url) {
  content = content.replace(/__META_TITLE__/g, title);
  content = content.replace(/__META_DESCRIPTION__/g, description);
  content = content.replace(/__META_URL__/g, url);
  return content;
}

async function setMetaTags(req, env, content) {
  let title, description, url;
  const urlPath = req.path;
  const domainName = env === PROD ? DOMAIN_NAME_PROD : DOMAIN_NAME_PPP;
  const [pageId, comedianId] = getPageId(urlPath);

  if (pageId === 'comedian') {
    const data = await getComedian(req);
    console.log(data);
    title = 'Standup comedian ';
    description = 'Browse videos of  on comedy collection';
    url = `https://${domainName}/comedians/${comedianId}`;
  } else if (pageId === 'comedians') {
    title = 'List of standup comedians';
    description = 'Browse your favourite comedians on comedy collection';
    url = `https://${domainName}/comedians`;
  } else if (pageId === 'search') {
    title = 'Search page for comedy collection';
    description = 'Search Comedian or Standup Videos on comedy collection';
    url = `https://${domainName}/search`;
  } else if (pageId === 'home') {
    title = 'Comedy Collection';
    description =
      'Enjoy the videos of comedians you love, and share it all with friends, family and people who need the dose of humour in their life.';
    url = `https://${domainName}`;
  }

  return updateMetaTags(content, title, description, url);
}

export const getHomeTemplate = async (req, res) => {
  const env = ['production'].includes(process.env.NODE_ENV) ? PROD : DEV;
  const templateName = 'index.html';
  const homePagePath = path.join(__dirname, `../../../build/${env}/${templateName}`);
  const readFile = util.promisify(fs.readFile);
  const content = await readFile(homePagePath, { encoding: 'utf8' });
  const contentWithMeta = await setMetaTags(req, env, content);
  res.set('Cache-Control', 'public, max-age=60, s-maxage=180');
  res.send(contentWithMeta);
};