-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebmentions.js
59 lines (50 loc) · 1.76 KB
/
webmentions.js
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
import fs from "fs";
import https from "https";
const DOMAIN = "www.bhekani.com";
const webmentions = await fetchWebmentions();
webmentions.forEach(writeWebMention);
function fetchWebmentions() {
const url =
"https://webmention.io/api/mentions.jf2" +
`?domain=${DOMAIN}` +
`&token=${process.env.WEBMENTION_API_KEY}` +
"&per-page=999";
return new Promise((resolve, reject) => {
const req = https.get(url, (res) => {
let body = "";
res.on("data", (chunk) => (body += chunk));
res.on("end", () => {
try {
const response = JSON.parse(body);
console.log("res.statusCode:", res.statusCode);
if (res.statusCode !== 200) reject(body);
console.log("response.children:", response.children);
resolve(response.children);
} catch (error) {
reject(error);
}
});
});
req.on("error", (error) => reject(error));
});
}
function writeWebMention(webmention) {
console.log("webmention:", webmention);
// Each post will have its own webmentions json file, named after the slug
const slug = webmention["wm-target"]
.replace(`https://${DOMAIN}/`, "")
.replace(/\/$/, "")
.replace("/", "--");
const filename = `./src/content/webmentions/${slug || "home"}.json`;
// Create the file if it doesn't exist
if (!fs.existsSync(filename)) {
fs.writeFileSync(filename, JSON.stringify([webmention], null, 2));
return;
}
// If the file already exists, append the new webmention while also deduping
const entries = JSON.parse(fs.readFileSync(filename))
.filter((wm) => wm["wm-id"] !== webmention["wm-id"])
.concat([webmention]);
entries.sort((a, b) => a["wm-id"] - b["wm-id"]);
fs.writeFileSync(filename, JSON.stringify(entries, null, 2));
}