Skip to content

Instantly share code, notes, and snippets.

@f0-x
Created July 3, 2023 04:27
Show Gist options
  • Save f0-x/5f26426a24bb8f4c562da5a47abfe3ef to your computer and use it in GitHub Desktop.
Save f0-x/5f26426a24bb8f4c562da5a47abfe3ef to your computer and use it in GitHub Desktop.
Validate the existence of Youtube and Vimeo Video
/**
* The function validates whether a given URL is a valid YouTube or Vimeo video link.
* @param {string} url - a string representing the URL of a video from either YouTube or Vimeo.
* @returns A function that takes a string parameter `url` and returns a Promise. The function checks
* if the `url` matches a YouTube URL regex and if the video ID is 11 characters long. If it is a
* YouTube URL, the function creates an image element with the video thumbnail URL and checks if the
* image has a width of 120 pixels. If it does, the function rejects the Promise with
*/
const YOUTUBE_URL_REGEX = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
export const validateYtAndVimeo = (url: string) => {
if (
url.match(YOUTUBE_URL_REGEX) &&
url.match(YOUTUBE_URL_REGEX)?.[2]?.length === 11
) {
return new Promise((resolve, reject) => {
let img = new Image();
const videoId = url.match(/([a-z0-9_-]{11})/gim)?.[0];
img.src = "http://img.youtube.com/vi/" + videoId + "/mqdefault.jpg";
img.addEventListener("load", function () {
if (this.width === 120) {
reject("Youtube video not found");
} else {
resolve(true);
}
});
});
} else {
return new Promise(async (resolve, reject) => {
const checkVimeoVideo = await fetch(`/api/validation/vimeo?url=${url}`);
if (checkVimeoVideo.ok) {
resolve(true);
} else {
reject("Vimeo video not found");
}
});
}
};
//API Route handler for Vimeo Video Validation
const VIMEO_OEMBED_URL = "https://vimeo.com/api/oembed.json?url=";
import axios from "axios";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const url = req.query.url;
const response = await axios({
method: "get",
url: VIMEO_OEMBED_URL?.concat(url as string),
responseType: "json",
headers: {},
});
res.status(200).json(response.data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment