Validating repository content with GitHub GraphQL API
Nicolas Santos
Posted on June 8, 2022
Let's start by seeing what the query is, and after that, explain by parts which are the meaning behind each expression and how we can handle the information.
query($owner: String!, $repositoryName: String!) {
repository(owner: $owner, name: $repositoryName) {
packageJson: object(expression: "HEAD:package.json") {
... on Blob {
byteSize,
text
}
}
}
}
Very simple, isn't it?
This query takes as query variables owner
, which is the owner of the repository, and repositoryName
.
First of all, we need to access the repository information, once we invoke the query for obtaining the infomration, we can get object
, this field allows an expression in which we're gonna specify the path of the file that we have to validate, in this case, HEAD:package.json
, but it can be wherever you want (the format is the following ${branch}:${pathFile}
).
After that, you have to obtain the Blob of this object, which includes byteSize
(aka the file size, or null
if it doesn't exist) and text(aka the content file).
And that's all!
With this query we can obtain something like
{
"data": {
"repository": {
"packageJson": {
"byteSize": 719,
"text": "{\n \"name\": \"test-repo\",\n \"version\": \"1.0.0\",\n \"author\": \"\",\n \"copyright\": \"\",\n \"scripts\": {\n \"dev\": \"zuplo dev\",\n \"build\": \"zuplo build\",\n \"test\": \"zuplo test\",\n \"postinstall\": \"husky install\"\n },\n \"dependencies\": {\n \"devDependencies\": {\n \"husky\": \"^7.0.4\"\n },\n \"packageManager\": \"yarn@3.1.0\"\n }\n}"
}
}
}
}
or if the file doesn't exist
{
"data": {
"repository": {
"packageJson": null
}
}
}
Posted on June 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.