-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
api.ts
311 lines (263 loc) · 6.96 KB
/
api.ts
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/**
* Collection of content-fetching and formatting methods.
*/
import dotenv from "dotenv"
import fs2 from "fs"
import path from "path"
import Slugger from "github-slugger"
import { Octokit } from "octokit"
import { GITHUB_REPO } from "./../const"
dotenv.config()
// Project-root-relative directory for temporary data used in local development
const DEVELOPMENT_CACHE_DIR = "cache"
let octokitInstance: Octokit
// Define variable if GITHUB_TOKEN is set and not empty
const githubTokenIsSet: boolean = (() => {
if (
process.env.hasOwnProperty("GITHUB_TOKEN") === false ||
process.env.GITHUB_TOKEN === ""
) {
// add warning for production builds
if (import.meta.env.MODE === "production") {
console.warn(
"GITHUB_TOKEN not set or empty. You can ignore this warning for local development."
)
}
return false
}
return true
})()
/**
* Returns an instance of Octokit, which uses the `GITHUB_TOKEN` environment
* variable for authentication.
* @returns Octokit
*/
const octokit = () => {
if (octokitInstance) {
return octokitInstance
}
octokitInstance = new Octokit({
auth: process.env.GITHUB_TOKEN,
})
return octokitInstance
}
/**
* Returns a URL-friendly slug for a given string.
* @param value
* @returns string
*/
export function getSlug(value: string) {
const slugger = new Slugger()
return slugger.slug(value)
}
/**
* Returns the URL for a category’s listing page.
* @param name The full category name
* @returns root-relative path
*/
export function getCategoryUrl(name: string) {
return `/blog/category/${getSlug(name)}`
}
/**
* Fetches GitHub Sponsors.
* @returns response data
*/
export async function getSponsors() {
if (!githubTokenIsSet) {
return []
}
const cacheFilename = "sponsors.json"
const cachedData = getCache(cacheFilename)
if (cachedData) {
return cachedData
}
const response = await octokit().graphql(`
query CombinedSponsors {
org: organization(login: "ddev") {
sponsors(first: 100) {
nodes {
... on User {
login
url
avatarUrl
}
... on Organization {
login
url
avatarUrl
}
}
}
}
user: user(login: "rfay") {
sponsors(first: 100) {
nodes {
... on User {
login
url
avatarUrl
}
... on Organization {
login
url
avatarUrl
}
}
}
}
}
`)
// Combine sponsors from both sources and remove duplicates
const allSponsors = [
...response.org.sponsors.nodes,
...response.user.sponsors.nodes,
].reduce((unique, sponsor) => {
// Use login as unique identifier
if (!unique.some((item) => item.login === sponsor.login)) {
unique.push(sponsor)
}
return unique
}, [])
putCache(cacheFilename, JSON.stringify(allSponsors))
return allSponsors
}
/**
* Fetches GitHub contributor data.
* @param useDevCache Whether to use a local result cache in development to reduce third-party calls.
* @returns response data
*/
export async function getContributors(includeAnonymous = false) {
if (!githubTokenIsSet) {
return []
}
const cacheFilename = "contributors.json"
const cachedData = getCache(cacheFilename)
let data
if (cachedData) {
data = cachedData
} else {
const response = await octokit().paginate(
`GET https://api.github.com/repos/${GITHUB_REPO}/contributors`,
{
anon: 1,
per_page: 100,
}
)
data = response
putCache(cacheFilename, JSON.stringify(data))
}
if (!includeAnonymous) {
return data.filter((contributor) => {
return contributor.type !== "Anonymous"
})
}
return data ?? []
}
/**
* Gets repository details from GitHub.
* https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#get-a-repository
*
* @param name The name of the repository, like `ddev/ddev`.
* @returns response data
*/
export async function getRepoDetails(name: string) {
if (!githubTokenIsSet) {
return []
}
const slug = name.replace("/", "-")
const cacheFilename = `repository-${slug}.json`
const cachedData = getCache(cacheFilename)
if (cachedData) {
return cachedData
}
const response = await octokit().request(
`GET https://api.github.com/repos/${name}`
)
const data = response.data
putCache(cacheFilename, JSON.stringify(data))
return data
}
/**
* Gets the most recent `ddev/ddev` tag name, like `v1.21.4`.
*
* @param stable Whether to return stable releases only (`true` by default).
* @returns tag name
*/
export async function getLatestReleaseVersion(stable = true) {
if (!githubTokenIsSet) {
return []
}
let data = await getReleases()
if (stable) {
data = data.filter((release) => {
return !release.draft && !release.prerelease
})
}
return data[0].tag_name
}
export async function getReleases() {
if (!githubTokenIsSet) {
return []
}
const cacheFilename = "releases.json"
const cachedData = getCache(cacheFilename)
if (cachedData) {
return cachedData
}
const response = await octokit().paginate(
`GET https://api.github.com/repos/${GITHUB_REPO}/releases`,
{
per_page: 100,
}
)
putCache(cacheFilename, JSON.stringify(response))
return response ?? []
}
/**
* Returns JSON-parsed value from a cached file if it exists.
* @param filename Name of the file to look for in the cache directory.
* @returns file contents or null
*/
const getCache = (filename: string) => {
const dir = path.resolve("./" + DEVELOPMENT_CACHE_DIR)
const filePath = dir + "/" + filename
if (fs2.existsSync(filePath)) {
const contents = fs2.readFileSync(filePath)
return JSON.parse(contents)
}
return
}
/**
* Write a file to the cache directory.
* @param filename Name of the file to write to the cache directory.
* @param contents Contents of the file.
*/
const putCache = (filename: string, contents: string) => {
const dir = path.resolve("./" + DEVELOPMENT_CACHE_DIR)
const filePath = dir + "/" + filename
if (!fs2.existsSync(dir)) {
fs2.mkdirSync(dir)
}
fs2.writeFileSync(filePath, contents)
}
/**
* Format a date string. Used mostly for blog post listing and detail pages.
*
* @param date The source date, which probably looks like `2021-01-28T13:05:28`.
* @param customOptions Options for [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat)
* @returns formatted date string
*/
export const formatDate = (date: string, customOptions?: object) => {
const pubDate = new Date(date)
const defaultOptions = {
timeZone: "UTC",
month: "short",
day: "numeric",
year: "numeric",
}
const options = {
...defaultOptions,
...customOptions,
}
return new Intl.DateTimeFormat("en-US", options).format(pubDate)
}