Avatar

@fab1an

6 likes13 public vals
Joined March 27, 2023
Fork
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
import { fetch } from "https://esm.town/v/std/fetch";
export const extractOnThisDayStory = async () => {
const getTodayDate = () => {
const date = new Date();
const MM = String(date.getMonth() + 1).padStart(2, "0");
const DD = String(date.getDate()).padStart(2, "0");
return { MM, DD };
};
const getOnThisDayContent = async (MM, DD) => {
const url =
`https://api.wikimedia.org/feed/v1/wikipedia/en/onthisday/all/${MM}/${DD}`;
try {
const response = await fetch(url);
const data = await response.json();
const newsEvents = data.events; // We assume that 'events' category is most likely to contain news articles.
if (!newsEvents.length)
throw new Error("No events found for this date.");
// Randomly select an event.
const randomEvent =
newsEvents[Math.floor(Math.random() * newsEvents.length)];
// Instead of returning a string, we return an object with a `data` property.
return { data: `${randomEvent.text} (${randomEvent.year})` };
}
catch (error) {
console.log("Error fetching On This Day content:", error);
return `An error occurred while fetching the On This Day content. ${error}`;
}
};
const { MM, DD } = getTodayDate();
return await getOnThisDayContent(MM, DD);
};
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
import { fetch } from "https://esm.town/v/std/fetch";
export const getRandomArticleInCategory = async (category) => {
try {
if (!category) {
throw new Error("Invalid input. Please provide a category as a string.");
}
const { DOMParser } = await import(
"https://deno.land/x/deno_dom/deno-dom-wasm.ts"
);
// Replace spaces with underscores in the category name, and URL encode it
const encodedCategory = encodeURIComponent(category.replace(/ /g, "_"));
const listUrl =
`https://en.wikipedia.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:${encodedCategory}&cmlimit=500&format=json&origin=*`;
const listResponse = await fetch(listUrl);
const listData = await listResponse.json();
if (!listData.query.categorymembers.length) {
throw new Error(`No Wikipedia articles found in category "${category}"`);
}
// Get a random article from the list
const randomArticle =
listData.query
.categorymembers[
Math.floor(Math.random() * listData.query.categorymembers.length)
].title;
const contentUrl =
`https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&titles=${
encodeURIComponent(randomArticle)
}&format=json&utf8=1&origin=*`;
const contentResponse = await fetch(contentUrl);
const contentData = await contentResponse.json();
const pageId = Object.keys(contentData.query.pages)[0];
const textContent = contentData.query.pages[pageId].extract;
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(textContent, "text/html");
const extractedText = htmlDoc.querySelector("body").textContent;
return `${extractedText.trim()}`;
}
catch (error) {
console.log("Error fetching Wikipedia content:", error);
return `An error occurred while fetching the Wikipedia content. ${error}`;
}
};
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
import { fetch } from "https://esm.town/v/std/fetch";
export async function getCNNNewsShort() {
const response = await fetch(
"https://saurav.tech/NewsAPI/everything/cnn.json"
);
const data = await response.json();
const { articles } = data;
// Function to strip HTML tags from a string
const stripHtmlTags = (str) => {
const regex = /(<([^>]+)>)/gi;
return str.replace(regex, "");
};
// Create an array to store trimmed articles
const trimmedArticles = [];
// Loop over the first 10 articles
for (let i = 0; i < Math.min(10, articles.length); i++) {
const article = articles[i];
const trimmedArticle = {
title: stripHtmlTags(article.title),
description: stripHtmlTags(article.description),
url: article.url,
};
trimmedArticles.push(trimmedArticle);
}
// Convert trimmedArticles array to a string using JSON.stringify()
const output = { data: JSON.stringify(trimmedArticles) };
return output;
}
1
2
3
4
5
6
7
8
9
10
import { fetch } from "https://esm.town/v/std/fetch";
export async function getCNNNews() {
const response = await fetch(
"https://saurav.tech/NewsAPI/everything/cnn.json"
);
const data = await response.json();
const output = { data };
return output;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { fetch } from "https://esm.town/v/std/fetch";
export const extractRandomCardImage = async () => {
try {
const response = await fetch(
"https://deckofcardsapi.com/api/deck/new/draw/?count=1"
);
const data = await response.json();
if (data.success && data.cards && data.cards.length > 0) {
const cardImage = data.cards[0].image;
return { data: cardImage };
} else {
throw new Error("No cards found in the response.");
}
} catch (error) {
console.log("Error fetching random card image:", error);
return {
data: `An error occurred while fetching the random card image. ${error}`,
};
}
};
Fork
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
import { fetch } from "https://esm.town/v/std/fetch";
export const extractRandomWords = async (req: Request) => {
try {
const response = await fetch("https://random-word-api.herokuapp.com/word?number=1");
if (!response.ok) {
// If the response is not OK, return an error message
throw new Error(`HTTP error! status: ${response.status}`);
}
const words = await response.json();
// Create a JSON object with the "data" field containing the words as a string
const responseData = { data: words.join(" ") };
// Return a Response object with JSON data
return new Response(JSON.stringify(responseData), {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.log("Error fetching random words:", error);
// Return an error message in a Response object
return new Response(JSON.stringify({ error: `An error occurred while fetching the random words. ${error}` }), {
headers: { "Content-Type": "application/json" },
status: 500, // Set an appropriate HTTP status code for errors
});
}
};
Fork
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { blob } from "https://esm.town/v/std/blob?v=10";
export const databin = async (req: Request) => {
const searchParams = new URL(req.url).searchParams;
const format = searchParams.get("format") ?? "json";
const key = searchParams.get("key");
if (!key) throw new Error("missing ?key=");
let data;
const oldData = await blob.getJSON(key);
if (req.method == "GET") {
data = { data: oldData };
} else if (req.method == "POST") {
const newData = await req.json();
await blob.setJSON(key, newData);
data = { oldData, data: newData };
console.log("set", { key, data });
}
else {
throw new Error("unsupported HTTP method");
}
return Response.json(data);
};
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
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
import process from "node:process";
export const browserlessScrapeExample = (async () => {
const res = await fetchJSON(
`https://chrome.browserless.io/scrape?token=${process.env.browserlessKey}`,
{
method: "POST",
body: JSON.stringify({
"url": "https://en.wikipedia.org/wiki/OpenAI",
"elements": [{
// The second <p> element on the page
"selector": "p:nth-of-type(2)",
}],
}),
},
);
// For this request, Browserless returns one data item
const data = res.data;
// That contains a single element
const elements = res.data[0].results;
// That we want to turn into its innerText value
const intro = elements[0].text;
return intro;
})();
Fork
1
2
3
4
5
6
7
8
9
10
export const returnDate = () => {
const getTodayDate = () => {
const date = new Date();
const options = { day: "numeric", month: "long" };
const formattedDate = date.toLocaleDateString("en-US", options);
return formattedDate;
};
const todayDate = getTodayDate();
return { data: todayDate };
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { fetch } from "https://esm.town/v/std/fetch";
export async function hnTopStory() {
const topStories: Number[] = await fetch(
"https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty"
).then((res) => res.json());
const id = topStories[0];
const story: {
title: string;
url: string;
time: number;
type: string;
score: number;
by: string;
} = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`).then(
(res) => res.json()
);
const data = { data: story.title };
return data;
}