aboutsummaryrefslogtreecommitdiff
path: root/apps/cf-ai-backend/src/queueConsumer/utils/get-metadata.ts
blob: 959165062ce27ce7d1b128921266fb4d74da783e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import * as cheerio from "cheerio";
import { Result, Ok, Err } from "../../errors/results";
import { BaseError } from "../../errors/baseError";

class GetMetadataError extends BaseError {
	constructor(message?: string, source?: string) {
		super("[Fetch Metadata Error]", message, source);
	}
}
export type Metadata = {
	title: string;
	description: string;
	image: string;
	baseUrl: string;
};
// TODO: THIS SHOULD PROBABLY ALSO FETCH THE OG-IMAGE
export async function getMetaData(
	url: string,
): Promise<Result<Metadata, GetMetadataError>> {
	try {
		const response = await fetch(url);
		const html = await response.text();

		const $ = cheerio.load(html);

		// Extract the base URL
		const baseUrl = url;

		// Extract title
		const title = $("title").text().trim();

		const description = $("meta[name=description]").attr("content") ?? "";

		const _favicon =
			$("link[rel=icon]").attr("href") ?? "https://supermemory.dhr.wtf/web.svg";

		let favicon =
			_favicon.trim().length > 0
				? _favicon.trim()
				: "https://supermemory.dhr.wtf/web.svg";
		if (favicon.startsWith("/")) {
			favicon = baseUrl + favicon;
		} else if (favicon.startsWith("./")) {
			favicon = baseUrl + favicon.slice(1);
		}

		return Ok({
			title,
			description,
			image: favicon,
			baseUrl,
		});
	} catch (e) {
		console.error("[Metadata Fetch Error]", e);
		return Err(new GetMetadataError((e as Error).message, "getMetaData"));
	}
}