Public
HTTP (deprecated)
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
58
59
// This val fetches the 10 most recent Mastodon posts using the Mastodon API.
// It requires a Mastodon access token stored in the MASTODON_TOKEN environment variable.
import axios from "npm:axios";
export default async function main(req: Request): Promise<Response> {
const token = Deno.env.get("MASTODON_TOKEN");
const instance = "mastodon.social"; // Replace with your Mastodon instance if different
if (!token) {
return Response.json({ error: "Mastodon access token not set" }, { status: 500 });
}
try {
const response = await axios.get(`https://${instance}/api/v1/accounts/verify_credentials`, {
headers: { Authorization: `Bearer ${token}` },
});
const userId = response.data.id;
const statusesResponse = await axios.get(`https://${instance}/api/v1/accounts/${userId}/statuses`, {
headers: { Authorization: `Bearer ${token}` },
params: { limit: 10, exclude_replies: true, exclude_reblogs: true },
});
const posts = statusesResponse.data.map(post => ({
id: post.id,
content: post.content,
created_at: post.created_at,
url: post.url,
favourites_count: post.favourites_count,
reblogs_count: post.reblogs_count,
}));
console.log(`Fetched ${posts.length} Mastodon posts`);
return Response.json(posts);
} catch (error) {
console.error("Error fetching Mastodon posts:", error);
let errorMessage = "An error occurred while fetching Mastodon posts";
if (axios.isAxiosError(error)) {
if (error.response) {
errorMessage += `: ${error.response.status} ${error.response.statusText}`;
if (error.response.data) {
errorMessage += ` - ${JSON.stringify(error.response.data)}`;
}
} else if (error.request) {
errorMessage += ": No response received from Mastodon API";
} else {
errorMessage += `: ${error.message}`;
}
} else if (error instanceof Error) {
errorMessage += `: ${error.message}`;
}
return Response.json({ error: errorMessage }, { status: 500 });
}
}
ejfox-mastodon.web.val.run
August 16, 2024