Last active
October 25, 2023 04:53
-
-
Save jordiup/9963acb172944bfac29c4c3d8634dab0 to your computer and use it in GitHub Desktop.
useful for fetching a last modified value from a blog post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getLastModifiedGitDate(filePath: string): Date { | |
filePath = 'README.md'; | |
const query = ` | |
{ | |
repository(owner: "jordiup", name: "sharehouse") { | |
ref(qualifiedName: "refs/heads/main") { | |
target { | |
... on Commit { | |
history(first: 1, path: "${filePath}") { | |
edges { | |
node { | |
committedDate | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
`; | |
const command = ` | |
curl -s -H "Authorization: Bearer ${'<INSERT TOKEN HERE>'}" \ | |
-H "Content-Type:application/json" \ | |
-d '${JSON.stringify({ query })}' \ | |
https://api.github.com/graphql | |
`; | |
try { | |
const output = execSync(command).toString(); | |
const data = JSON.parse(output); | |
console.log(data); | |
const committedDate = | |
data?.data?.repository?.ref?.target?.history?.edges?.[0]?.node | |
?.committedDate; | |
if (committedDate) { | |
return new Date(committedDate); | |
} else { | |
throw new Error('No committed date found'); | |
} | |
} catch (error) { | |
console.error( | |
`Error fetching last modified date for ${filePath}`, | |
error, | |
); | |
// Return current date as a fallback, or you could throw the error or return a default date. | |
return new Date(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment