[dyad] Created a meta tag extractor app - wrote 5 file(s), added cheerio package(s)
This commit is contained in:
47
src/app/actions.ts
Normal file
47
src/app/actions.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
"use server";
|
||||
|
||||
import * as cheerio from "cheerio";
|
||||
|
||||
export async function extractMetaData(url: string) {
|
||||
if (!url) {
|
||||
return { error: "URL is required." };
|
||||
}
|
||||
|
||||
let formattedUrl = url;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
formattedUrl = `https://${url}`;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(formattedUrl, {
|
||||
headers: {
|
||||
"User-Agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return { error: `Failed to fetch URL. Status: ${response.status}` };
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
const $ = cheerio.load(html);
|
||||
|
||||
const title =
|
||||
$('meta[property="og:title"]').attr("content") ||
|
||||
$("title").text() ||
|
||||
"No title found";
|
||||
const description =
|
||||
$('meta[property="og:description"]').attr("content") ||
|
||||
$('meta[name="description"]').attr("content") ||
|
||||
"No description found";
|
||||
|
||||
return { data: { title, description } };
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
if (error instanceof Error && error.message.includes('Invalid URL')) {
|
||||
return { error: "The provided URL is not valid. Please check and try again." };
|
||||
}
|
||||
return { error: "An unexpected error occurred while fetching the URL." };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user