Validating repository content with GitHub GraphQL API
June 07, 2022 •
☕️
2 min read
Let's say that you are trying to validate if a repository has a series of files, or package.json
has a specific dependency, or one of these files has a particular format that you need to corroborate.
With GitHub GraphQL API you can check the size of the file (which we can use to check if the file exists or not) is, and the content of it.
Disclaimer: In this article, we assume you know how to authorize and use GitHub GraphQL API, for more information here's the documentation.
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
}
}
}