Skip to content

Commit 78d6728

Browse files
authored
Convert gatsby-node to TypeScript (#1343)
1 parent d12985f commit 78d6728

File tree

2 files changed

+119
-95
lines changed

2 files changed

+119
-95
lines changed

gatsby-node.js renamed to gatsby-node.ts

Lines changed: 47 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,33 @@
1-
const path = require("node:path")
2-
const sortLibs = require("./scripts/sort-libraries")
3-
const globby = require("globby")
4-
const frontmatterParser = require("parser-front-matter")
5-
const { readFile } = require("node:fs/promises")
6-
const { promisify } = require("node:util")
1+
import { GatsbyNode } from "gatsby"
2+
import * as path from "path"
3+
import { promisify } from "util"
4+
import { readFile } from "fs/promises"
5+
import * as globby from "globby"
6+
import * as frontmatterParser from "parser-front-matter"
7+
import { sortLibs } from "./scripts/sort-libraries"
78

89
const parse$ = promisify(frontmatterParser.parse)
910

10-
exports.createSchemaCustomization = ({ actions }) => {
11-
const gql = String.raw
12-
const { createTypes } = actions
13-
14-
createTypes(gql`
15-
type BlogPost implements Node @childOf(types: ["MarkdownRemark"]) {
16-
postId: String!
17-
title: String!
18-
tags: [String!]!
19-
date: Date! @dateformat(formatString: "YYYY-MM-DD")
20-
authors: [String!]!
21-
guestBio: String
22-
remark: MarkdownRemark! @link # backlink to the parent
23-
}
24-
`)
25-
}
11+
export const createSchemaCustomization: GatsbyNode["createSchemaCustomization"] =
12+
async ({ actions }) => {
13+
const gql = String.raw
14+
const { createTypes } = actions
15+
16+
createTypes(gql`
17+
type BlogPost implements Node @childOf(types: ["MarkdownRemark"]) {
18+
postId: String!
19+
title: String!
20+
tags: [String!]!
21+
date: Date! @dateformat(formatString: "YYYY-MM-DD")
22+
authors: [String!]!
23+
guestBio: String
24+
remark: MarkdownRemark! @link # backlink to the parent
25+
}
26+
`)
27+
}
2628

2729
// Transform nodes, each of logic inside here can be extracted to a separated plugin later.
28-
exports.onCreateNode = async ({
30+
export const onCreateNode: GatsbyNode["onCreateNode"] = async ({
2931
reporter,
3032
node,
3133
actions,
@@ -79,7 +81,10 @@ exports.onCreateNode = async ({
7981
}
8082
}
8183

82-
exports.onCreatePage = async ({ page, actions }) => {
84+
export const onCreatePage: GatsbyNode["onCreatePage"] = async ({
85+
page,
86+
actions,
87+
}) => {
8388
// trying to refactor code to be "the Gatsby way".
8489
// from the paths on ready, ignores a bunch of existing custom logic below.
8590
if (page.path.startsWith("/blog")) {
@@ -93,11 +98,11 @@ exports.onCreatePage = async ({ page, actions }) => {
9398
deletePage(page)
9499
let context = {
95100
...page.context,
96-
sourcePath: path.relative(__dirname, page.componentPath),
101+
sourcePath: path.relative(__dirname, page.path),
97102
}
98103
if (page.path === "/code" || page.path === "/code/") {
99104
const markdownFilePaths = await globby("src/content/code/**/*.md")
100-
const codeData = {}
105+
const codeData: any = {}
101106
const slugMap = require("./src/content/code/slug-map.json")
102107
await Promise.all(
103108
markdownFilePaths.map(async markdownFilePath => {
@@ -171,8 +176,8 @@ exports.onCreatePage = async ({ page, actions }) => {
171176
}
172177
})
173178
)
174-
const languageList = []
175-
const toolList = []
179+
const languageList: any = []
180+
const toolList: any = []
176181
await Promise.all([
177182
...Object.keys(codeData.Languages).map(async languageName => {
178183
const libraryCategoryMap = codeData.Languages[languageName]
@@ -242,11 +247,14 @@ exports.onCreatePage = async ({ page, actions }) => {
242247
})
243248
}
244249

245-
exports.createPages = async ({ graphql, actions }) => {
250+
export const createPages: GatsbyNode["createPages"] = async ({
251+
actions,
252+
graphql,
253+
}) => {
246254
const { createPage } = actions
247255

248256
const result = await graphql(`
249-
{
257+
query allMarkdownRemark {
250258
allMarkdownRemark {
251259
edges {
252260
node {
@@ -493,12 +501,13 @@ exports.createPages = async ({ graphql, actions }) => {
493501
}
494502
}
495503

496-
exports.onCreateWebpackConfig = ({ actions }) => {
497-
actions.setWebpackConfig({
498-
resolve: {
499-
fallback: {
500-
assert: require.resolve("assert/"),
504+
export const onCreateWebpackConfig: GatsbyNode["onCreateWebpackConfig"] =
505+
async ({ actions }) => {
506+
actions.setWebpackConfig({
507+
resolve: {
508+
fallback: {
509+
assert: "assert/",
510+
},
501511
},
502-
},
503-
})
504-
}
512+
})
513+
}

scripts/sort-libraries.js renamed to scripts/sort-libraries.ts

Lines changed: 72 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const fetch = require(`node-fetch`)
21
const numbro = require("numbro")
32
const timeago = require("timeago.js")
43

@@ -113,7 +112,7 @@ const getGitHubStats = async githubRepo => {
113112
average: true,
114113
})
115114

116-
const releases = []
115+
const releases: any = []
117116
if (
118117
repo.tags &&
119118
repo.tags.nodes &&
@@ -142,78 +141,94 @@ const getGitHubStats = async githubRepo => {
142141
}
143142
}
144143

145-
const getNpmStats = async packageName => {
144+
async function getNpmStats(packageName: string): Promise<number> {
146145
const response = await fetch(
147146
`https://api.npmjs.org/downloads/point/last-week/${encodeURIComponent(
148147
packageName
149148
)}`
150149
)
151150
const responseJson = await response.json()
152151
const downloadCount = responseJson.downloads
153-
return { downloadCount }
152+
if (!downloadCount) {
153+
console.debug(
154+
`getNpmStats: No download count for ${packageName}, so value is 0!`
155+
)
156+
return 0
157+
}
158+
return downloadCount
154159
}
155160

156-
const getGemStats = async packageName => {
161+
async function getGemStats(packageName: string): Promise<number> {
157162
const response = await fetch(
158163
`https://rubygems.org/api/v1/gems/${encodeURIComponent(packageName)}.json`
159164
)
160165
const responseJson = await response.json()
161166
const downloadCount = responseJson.downloads
162-
return { downloadCount }
167+
console.debug(`getGemStats: ${downloadCount} for ${packageName}`)
168+
if (!downloadCount) {
169+
console.debug(
170+
`getGemStats: No download count for ${packageName}, so value is 0!`
171+
)
172+
return 0
173+
}
174+
return downloadCount
163175
}
164176

165-
const sortLibs = async libs => {
166-
let totalStars = 0
167-
const libsWithScores = await Promise.all(
168-
libs.map(async lib => {
169-
const [npmStats = {}, gemStars = {}, githubStats = {}] =
170-
await Promise.all([
171-
lib.npm && getNpmStats(lib.npm),
172-
lib.gem && getGemStats(lib.gem),
173-
lib.github && getGitHubStats(lib.github),
174-
])
175-
const result = {
176-
...lib,
177-
...npmStats,
178-
...gemStars,
179-
...githubStats,
177+
export async function sortLibs(libs: any) {
178+
{
179+
let totalStars = 0
180+
const libsWithScores = await Promise.all(
181+
libs.map(async lib => {
182+
console.log(`Fetching stats for ${lib.name}`)
183+
console.log(`Fetching gem for ${lib.gem}`)
184+
console.log(`Fetching github for ${lib.github}`)
185+
const [npmStats = {}, gemStars = {}, githubStats = {}] =
186+
await Promise.all([
187+
lib.npm && (await getNpmStats(lib.npm)),
188+
lib.gem && (await getGemStats(lib.gem)),
189+
lib.github && (await getGitHubStats(lib.github)),
190+
])
191+
const result = {
192+
...lib,
193+
...npmStats,
194+
...gemStars,
195+
...githubStats,
196+
}
197+
totalStars += result.stars || 0
198+
return result
199+
})
200+
)
201+
const sortedLibs = libsWithScores.sort((a, b) => {
202+
let aScore = 0,
203+
bScore = 0
204+
if ("downloadCount" in a && "downloadCount" in b) {
205+
if (a.downloadCount > b.downloadCount) {
206+
aScore += 40
207+
} else if (b.downloadCount > a.downloadCount) {
208+
bScore += 40
209+
}
180210
}
181-
totalStars += result.stars || 0
182-
return result
183-
})
184-
)
185-
const sortedLibs = libsWithScores.sort((a, b) => {
186-
let aScore = 0,
187-
bScore = 0
188-
if ("downloadCount" in a && "downloadCount" in b) {
189-
if (a.downloadCount > b.downloadCount) {
190-
aScore += 40
191-
} else if (b.downloadCount > a.downloadCount) {
192-
bScore += 40
211+
if ("hasCommitsInLast3Months" in a && a.hasCommitsInLast3Months) {
212+
aScore += 30
193213
}
194-
}
195-
if ("hasCommitsInLast3Months" in a && a.hasCommitsInLast3Months) {
196-
aScore += 30
197-
}
198-
if ("hasCommitsInLast3Months" in b && b.hasCommitsInLast3Months) {
199-
bScore += 30
200-
}
201-
if ("stars" in a && "stars" in b) {
202-
if (a.stars > b.stars) {
203-
aScore += 40
204-
} else if (a.stars < b.stars) {
205-
bScore += 40
214+
if ("hasCommitsInLast3Months" in b && b.hasCommitsInLast3Months) {
215+
bScore += 30
206216
}
207-
}
208-
if (bScore > aScore) {
209-
return 1
210-
}
211-
if (bScore < aScore) {
212-
return -1
213-
}
214-
return 0
215-
})
216-
return { sortedLibs, totalStars }
217+
if ("stars" in a && "stars" in b) {
218+
if (a.stars > b.stars) {
219+
aScore += 40
220+
} else if (a.stars < b.stars) {
221+
bScore += 40
222+
}
223+
}
224+
if (bScore > aScore) {
225+
return 1
226+
}
227+
if (bScore < aScore) {
228+
return -1
229+
}
230+
return 0
231+
})
232+
return { sortedLibs, totalStars }
233+
}
217234
}
218-
219-
module.exports = sortLibs

0 commit comments

Comments
 (0)