DEV Community

Cover image for Validating repository content with GitHub GraphQL API
Nicolas Santos
Nicolas Santos

Posted on • Originally published at santosnicolas.com

Validating repository content with GitHub GraphQL API

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
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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}"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

or if the file doesn't exist

{
  "data": {
    "repository": {
      "packageJson": null
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)