-
Notifications
You must be signed in to change notification settings - Fork 1
/
feed.mjs
82 lines (74 loc) · 1.91 KB
/
feed.mjs
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* eslint-disable global-require */
import { Feed } from "feed";
import path from "path";
import dotenv from "dotenv";
import fetch from "node-fetch";
import fs from "fs";
if (process.env.NODE_ENV !== "production") {
dotenv.config({ path: path.resolve(process.cwd(), ".env.local") });
}
async function fetchAPI(query, { variables } = {}) {
const res = await fetch("https://graphql.datocms.com/", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.DATO}`,
},
body: JSON.stringify({
query,
variables,
}),
});
const json = await res.json();
if (json.errors) {
console.error(json.errors);
throw new Error("Failed to fetch API");
}
return json.data;
}
async function getAllBlogs() {
const data = await fetchAPI(`
{
allArticles(orderBy: date_DESC) {
slug
title
description
date
}
}
`);
return data.allArticles;
}
const siteUrl = "https://samrobbins.uk";
const feed = new Feed({
title: "Sam Robbins' Blog",
description: "Posts about web development and more",
id: siteUrl,
link: siteUrl,
language: "en",
image: `${siteUrl}/favicon.svg`,
favicon: `${siteUrl}/favicon.svg`,
copyright: `All rights reserved ${new Date().getFullYear()}, Sam Robbins`,
feedLinks: {
rss: `${siteUrl}/feed.xml`,
json: `${siteUrl}/feed.json`,
atom: `${siteUrl}/atom.xml`,
},
author: {
name: "Sam Robbins",
link: "https://twitter.com/samrobbins85",
},
});
const blogs = await getAllBlogs();
blogs.forEach((post) => {
feed.addItem({
title: post.title,
id: siteUrl + "/blog/" + post.slug,
link: siteUrl + "/blog/" + post.slug,
description: post.description,
date: new Date(post.date),
});
});
fs.writeFileSync("./public/feed.xml", feed.rss2());
fs.writeFileSync("./public/atom.xml", feed.atom1());
fs.writeFileSync("./public/feed.json", feed.json1());