-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_blog.ts
More file actions
54 lines (43 loc) · 1.76 KB
/
Copy pathfetch_blog.ts
File metadata and controls
54 lines (43 loc) · 1.76 KB
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
import path from "path";
import * as cheerio from "cheerio";
import type { AnyNode } from "domhandler";
import type { BlogData, BlogPost } from "./src/types/data";
const BLOG_URL: string = "https://blog.uint.dev/";
const SELECTOR: string = ".listing .card";
const POST_LIMIT: number = 5;
const BLOG_TITLE: string = "Recent posts";
const BLOG_DESCRIPTION: string = `View all <a href="${BLOG_URL}">here</a>.`;
const blogEntryObject: BlogData = {
metadata: {
title: BLOG_TITLE,
description: BLOG_DESCRIPTION,
},
posts: [],
};
const filePath: string = path.join("./src/data", "blog.json");
async function fetchPosts(): Promise<BlogPost[]> {
const response: Response = await fetch(BLOG_URL, { signal: AbortSignal.timeout(10000) });
if (!response.ok) throw new Error(`Failed to fetch ${BLOG_URL}: ${response.status} ${response.statusText}`);
const $: cheerio.CheerioAPI = cheerio.load(await response.text());
const cards: cheerio.Cheerio<AnyNode> = $(SELECTOR);
if (!cards.length) throw new Error(`No elements found with selector '${SELECTOR}'`);
return cards
.slice(0, POST_LIMIT)
.toArray()
.map((el: AnyNode): BlogPost => {
const card: cheerio.Cheerio<AnyNode> = $(el);
return {
link: new URL(card.attr("href") ?? "", BLOG_URL).href,
title: card.find(".title").eq(0).text(),
description: card.find(".description").eq(0).text(),
metadata: card.find(".metadata").eq(0).html() ?? "",
};
});
}
console.log("Fetching blog post data...");
blogEntryObject.posts = await fetchPosts();
console.log(blogEntryObject);
console.log(`Writing to ${filePath}...`);
await Bun.write(filePath, JSON.stringify(blogEntryObject, null, 2));
console.log(`Successfully wrote to ${filePath}`);
console.log("Creating build...");