Skip to content

Convert gatsby-node to TypeScript #1343

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 47 additions & 38 deletions gatsby-node.js → gatsby-node.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
const path = require("node:path")
const sortLibs = require("./scripts/sort-libraries")
const globby = require("globby")
const frontmatterParser = require("parser-front-matter")
const { readFile } = require("node:fs/promises")
const { promisify } = require("node:util")
import { GatsbyNode } from "gatsby"
import * as path from "path"
import { promisify } from "util"
import { readFile } from "fs/promises"
import * as globby from "globby"
import * as frontmatterParser from "parser-front-matter"
import { sortLibs } from "./scripts/sort-libraries"

const parse$ = promisify(frontmatterParser.parse)

exports.createSchemaCustomization = ({ actions }) => {
const gql = String.raw
const { createTypes } = actions

createTypes(gql`
type BlogPost implements Node @childOf(types: ["MarkdownRemark"]) {
postId: String!
title: String!
tags: [String!]!
date: Date! @dateformat(formatString: "YYYY-MM-DD")
authors: [String!]!
guestBio: String
remark: MarkdownRemark! @link # backlink to the parent
}
`)
}
export const createSchemaCustomization: GatsbyNode["createSchemaCustomization"] =
async ({ actions }) => {
const gql = String.raw
const { createTypes } = actions

createTypes(gql`
type BlogPost implements Node @childOf(types: ["MarkdownRemark"]) {
postId: String!
title: String!
tags: [String!]!
date: Date! @dateformat(formatString: "YYYY-MM-DD")
authors: [String!]!
guestBio: String
remark: MarkdownRemark! @link # backlink to the parent
}
`)
}

// Transform nodes, each of logic inside here can be extracted to a separated plugin later.
exports.onCreateNode = async ({
export const onCreateNode: GatsbyNode["onCreateNode"] = async ({
reporter,
node,
actions,
Expand Down Expand Up @@ -79,7 +81,10 @@ exports.onCreateNode = async ({
}
}

exports.onCreatePage = async ({ page, actions }) => {
export const onCreatePage: GatsbyNode["onCreatePage"] = async ({
page,
actions,
}) => {
// trying to refactor code to be "the Gatsby way".
// from the paths on ready, ignores a bunch of existing custom logic below.
if (page.path.startsWith("/blog")) {
Expand All @@ -93,11 +98,11 @@ exports.onCreatePage = async ({ page, actions }) => {
deletePage(page)
let context = {
...page.context,
sourcePath: path.relative(__dirname, page.componentPath),
sourcePath: path.relative(__dirname, page.path),
}
if (page.path === "/code" || page.path === "/code/") {
const markdownFilePaths = await globby("src/content/code/**/*.md")
const codeData = {}
const codeData: any = {}
const slugMap = require("./src/content/code/slug-map.json")
await Promise.all(
markdownFilePaths.map(async markdownFilePath => {
Expand Down Expand Up @@ -171,8 +176,8 @@ exports.onCreatePage = async ({ page, actions }) => {
}
})
)
const languageList = []
const toolList = []
const languageList: any = []
const toolList: any = []
await Promise.all([
...Object.keys(codeData.Languages).map(async languageName => {
const libraryCategoryMap = codeData.Languages[languageName]
Expand Down Expand Up @@ -242,11 +247,14 @@ exports.onCreatePage = async ({ page, actions }) => {
})
}

exports.createPages = async ({ graphql, actions }) => {
export const createPages: GatsbyNode["createPages"] = async ({
actions,
graphql,
}) => {
const { createPage } = actions

const result = await graphql(`
{
query allMarkdownRemark {
allMarkdownRemark {
edges {
node {
Expand Down Expand Up @@ -493,12 +501,13 @@ exports.createPages = async ({ graphql, actions }) => {
}
}

exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
fallback: {
assert: require.resolve("assert/"),
export const onCreateWebpackConfig: GatsbyNode["onCreateWebpackConfig"] =
async ({ actions }) => {
actions.setWebpackConfig({
resolve: {
fallback: {
assert: "assert/",
},
},
},
})
}
})
}
129 changes: 72 additions & 57 deletions scripts/sort-libraries.js → scripts/sort-libraries.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const fetch = require(`node-fetch`)
const numbro = require("numbro")
const timeago = require("timeago.js")

Expand Down Expand Up @@ -113,7 +112,7 @@ const getGitHubStats = async githubRepo => {
average: true,
})

const releases = []
const releases: any = []
if (
repo.tags &&
repo.tags.nodes &&
Expand Down Expand Up @@ -142,78 +141,94 @@ const getGitHubStats = async githubRepo => {
}
}

const getNpmStats = async packageName => {
async function getNpmStats(packageName: string): Promise<number> {
const response = await fetch(
`https://api.npmjs.org/downloads/point/last-week/${encodeURIComponent(
packageName
)}`
)
const responseJson = await response.json()
const downloadCount = responseJson.downloads
return { downloadCount }
if (!downloadCount) {
console.debug(
`getNpmStats: No download count for ${packageName}, so value is 0!`
)
return 0
}
return downloadCount
}

const getGemStats = async packageName => {
async function getGemStats(packageName: string): Promise<number> {
const response = await fetch(
`https://rubygems.org/api/v1/gems/${encodeURIComponent(packageName)}.json`
)
const responseJson = await response.json()
const downloadCount = responseJson.downloads
return { downloadCount }
console.debug(`getGemStats: ${downloadCount} for ${packageName}`)
if (!downloadCount) {
console.debug(
`getGemStats: No download count for ${packageName}, so value is 0!`
)
return 0
}
return downloadCount
}

const sortLibs = async libs => {
let totalStars = 0
const libsWithScores = await Promise.all(
libs.map(async lib => {
const [npmStats = {}, gemStars = {}, githubStats = {}] =
await Promise.all([
lib.npm && getNpmStats(lib.npm),
lib.gem && getGemStats(lib.gem),
lib.github && getGitHubStats(lib.github),
])
const result = {
...lib,
...npmStats,
...gemStars,
...githubStats,
export async function sortLibs(libs: any) {
{
let totalStars = 0
const libsWithScores = await Promise.all(
libs.map(async lib => {
console.log(`Fetching stats for ${lib.name}`)
console.log(`Fetching gem for ${lib.gem}`)
console.log(`Fetching github for ${lib.github}`)
const [npmStats = {}, gemStars = {}, githubStats = {}] =
await Promise.all([
lib.npm && (await getNpmStats(lib.npm)),
lib.gem && (await getGemStats(lib.gem)),
lib.github && (await getGitHubStats(lib.github)),
])
const result = {
...lib,
...npmStats,
...gemStars,
...githubStats,
}
totalStars += result.stars || 0
return result
})
)
const sortedLibs = libsWithScores.sort((a, b) => {
let aScore = 0,
bScore = 0
if ("downloadCount" in a && "downloadCount" in b) {
if (a.downloadCount > b.downloadCount) {
aScore += 40
} else if (b.downloadCount > a.downloadCount) {
bScore += 40
}
}
totalStars += result.stars || 0
return result
})
)
const sortedLibs = libsWithScores.sort((a, b) => {
let aScore = 0,
bScore = 0
if ("downloadCount" in a && "downloadCount" in b) {
if (a.downloadCount > b.downloadCount) {
aScore += 40
} else if (b.downloadCount > a.downloadCount) {
bScore += 40
if ("hasCommitsInLast3Months" in a && a.hasCommitsInLast3Months) {
aScore += 30
}
}
if ("hasCommitsInLast3Months" in a && a.hasCommitsInLast3Months) {
aScore += 30
}
if ("hasCommitsInLast3Months" in b && b.hasCommitsInLast3Months) {
bScore += 30
}
if ("stars" in a && "stars" in b) {
if (a.stars > b.stars) {
aScore += 40
} else if (a.stars < b.stars) {
bScore += 40
if ("hasCommitsInLast3Months" in b && b.hasCommitsInLast3Months) {
bScore += 30
}
}
if (bScore > aScore) {
return 1
}
if (bScore < aScore) {
return -1
}
return 0
})
return { sortedLibs, totalStars }
if ("stars" in a && "stars" in b) {
if (a.stars > b.stars) {
aScore += 40
} else if (a.stars < b.stars) {
bScore += 40
}
}
if (bScore > aScore) {
return 1
}
if (bScore < aScore) {
return -1
}
return 0
})
return { sortedLibs, totalStars }
}
}

module.exports = sortLibs