Open
Description
Issue
The Date on the latest talk shows 1970.
I suspect the problem could be in the code since the YouTube page displayed "Apr 14, 2023" and should have returned the data accordingly. I noticed there are some suggestions for improvement in the current code.
Current Codeblock
I suspected the code formatting to be the issue, so went searching for the culprit. But what I found was a suggestion for improvement.
function getTechTalksData() {
return hygraphResponse.techTalks.map((talk) => {
const rgx = /(v=([\w-]+))|(be\/([\w-]+))/; // there's probably room for improvement here
talk.formattedDate = DateFormatters.fullDateShortMonth(
new Date(talk.dateAndTime),
);
talk.youTubeEmbedUrl = null;
if (talk.youTubeUrl) {
// source = https://www.youtube.com/watch?v=3mci0a8AWnI
// source = https://youtu.be/FU7v7JI5-pg
// target = https://www.youtube.com/embed/3mci0a8AWnI
const matches = talk.youTubeUrl.match(rgx);
if (matches) {
// depending on the format of the input URL, the slug will be
// at either position 2 or position 4 of the `matches` array
const id = matches[2] || matches[4];
talk.youTubeEmbedUrl = `https://www.youtube.com/embed/${id}`;
}
}
return talk;
});
}
Suggested Changes
We can break up the code into functional bite-size chunks to improve its quality and readability, while also adding additional functions like error catching. This should make the code more manageable. Will need testing before release.
// Extracts the YouTube video ID from a YouTube video URL
function extractYouTubeId(url) {
// Matches various formats of YouTube URLs
const regex = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|\?v=|\&v=)([^#\&\?]*).*/;
// Attempts to match the URL with the regular expression
const match = url.match(regex);
// Returns the ID if it exists, otherwise returns null
return match && match[2] ? match[2] : null;
}
// Formats a single talk object by adding a formatted date and YouTube embed URL
function formatTalk(talk) {
const formattedDate = DateFormatters.fullDateShortMonth(new Date(talk.dateAndTime));
const youTubeId = extractYouTubeId(talk.youTubeUrl);
// Constructs the YouTube embed URL from the ID (or null if there is no ID)
const youTubeEmbedUrl = youTubeId ? `https://www.youtube.com/embed/${youTubeId}` : null;
return { ...talk, formattedDate, youTubeEmbedUrl };
}
// Gets an array of formatted talk objects by mapping the `formatTalk` function over the `techTalks` array
function getTechTalksData() {
try {
// Maps the `formatTalk` function over the `techTalks` array to format each talk object
return hygraphResponse.techTalks.map(formatTalk);
} catch (error) {
// Logs any errors that occur
console.error(error);
// Returns an empty array if there is an error
return [];
}
}
Metadata
Assignees
Labels
No labels