8.0.1 • Published 20 days ago

@octokit/graphql v8.0.1

Weekly downloads
1,471,354
License
MIT
Repository
github
Last release
20 days ago

graphql.js

GitHub GraphQL API client for browsers and Node

@latest Build Status

Usage

Load @octokit/graphql directly from esm.sh

<script type="module">
  import { graphql } from "https://esm.sh/@octokit/graphql";
</script>

Install with npm install @octokit/graphql

import { graphql } from "@octokit/graphql";

Send a simple query

const { repository } = await graphql(
  `
    {
      repository(owner: "octokit", name: "graphql.js") {
        issues(last: 3) {
          edges {
            node {
              title
            }
          }
        }
      }
    }
  `,
  {
    headers: {
      authorization: `token secret123`,
    },
  },
);

Authentication

The simplest way to authenticate a request is to set the Authorization header, e.g. to a personal access token.

const graphqlWithAuth = graphql.defaults({
  headers: {
    authorization: `token secret123`,
  },
});
const { repository } = await graphqlWithAuth(`
  {
    repository(owner: "octokit", name: "graphql.js") {
      issues(last: 3) {
        edges {
          node {
            title
          }
        }
      }
    }
  }
`);

For more complex authentication strategies such as GitHub Apps or Basic, we recommend the according authentication library exported by @octokit/auth.

const { createAppAuth } = await import("@octokit/auth-app");
const auth = createAppAuth({
  appId: process.env.APP_ID,
  privateKey: process.env.PRIVATE_KEY,
  installationId: 123,
});
const graphqlWithAuth = graphql.defaults({
  request: {
    hook: auth.hook,
  },
});

const { repository } = await graphqlWithAuth(
  `{
    repository(owner: "octokit", name: "graphql.js") {
      issues(last: 3) {
        edges {
          node {
            title
          }
        }
      }
    }
  }`,
);

Variables

⚠️ Do not use template literals in the query strings as they make your code vulnerable to query injection attacks (see #2). Use variables instead:

const { repository } = await graphql(
  `
    query lastIssues($owner: String!, $repo: String!, $num: Int = 3) {
      repository(owner: $owner, name: $repo) {
        issues(last: $num) {
          edges {
            node {
              title
            }
          }
        }
      }
    }
  `,
  {
    owner: "octokit",
    repo: "graphql.js",
    headers: {
      authorization: `token secret123`,
    },
  },
);

Pass query together with headers and variables

import { graphql } from("@octokit/graphql");
const { repository } = await graphql({
  query: `query lastIssues($owner: String!, $repo: String!, $num: Int = 3) {
    repository(owner: $owner, name: $repo) {
      issues(last: $num) {
        edges {
          node {
            title
          }
        }
      }
    }
  }`,
  owner: "octokit",
  repo: "graphql.js",
  headers: {
    authorization: `token secret123`,
  },
});

Use with GitHub Enterprise

import { graphql } from "@octokit/graphql";
graphql = graphql.defaults({
  baseUrl: "https://github-enterprise.acme-inc.com/api",
  headers: {
    authorization: `token secret123`,
  },
});
const { repository } = await graphql(`
  {
    repository(owner: "acme-project", name: "acme-repo") {
      issues(last: 3) {
        edges {
          node {
            title
          }
        }
      }
    }
  }
`);

Use custom @octokit/request instance

import { request } from "@octokit/request";
import { withCustomRequest } from "@octokit/graphql";

let requestCounter = 0;
const myRequest = request.defaults({
  headers: {
    authorization: "bearer secret123",
  },
  request: {
    hook(request, options) {
      requestCounter++;
      return request(options);
    },
  },
});
const myGraphql = withCustomRequest(myRequest);
await request("/");
await myGraphql(`
  {
    repository(owner: "acme-project", name: "acme-repo") {
      issues(last: 3) {
        edges {
          node {
            title
          }
        }
      }
    }
  }
`);
// requestCounter is now 2

TypeScript

@octokit/graphql is exposing proper types for its usage with TypeScript projects.

Additional Types

Additionally, GraphQlQueryResponseData has been exposed to users:

import type { GraphQlQueryResponseData } from "@octokit/graphql";

Errors

In case of a GraphQL error, error.message is set to a combined message describing all errors returned by the endpoint. All errors can be accessed at error.errors. error.request has the request options such as query, variables and headers set for easier debugging.

import { graphql, GraphqlResponseError } from "@octokit/graphql";
graphql = graphql.defaults({
  headers: {
    authorization: `token secret123`,
  },
});
const query = `{
  viewer {
    bioHtml
  }
}`;

try {
  const result = await graphql(query);
} catch (error) {
  if (error instanceof GraphqlResponseError) {
    // do something with the error, allowing you to detect a graphql response error,
    // compared to accidentally catching unrelated errors.

    // server responds with an object like the following (as an example)
    // class GraphqlResponseError {
    //  "headers": {
    //    "status": "403",
    //  },
    //  "data": null,
    //  "errors": [{
    //   "message": "Field 'bioHtml' doesn't exist on type 'User'",
    //   "locations": [{
    //    "line": 3,
    //    "column": 5
    //   }]
    //  }]
    // }

    console.log("Request failed:", error.request); // { query, variables: {}, headers: { authorization: 'token secret123' } }
    console.log(error.message); // Field 'bioHtml' doesn't exist on type 'User'
  } else {
    // handle non-GraphQL error
  }
}

Partial responses

A GraphQL query may respond with partial data accompanied by errors. In this case we will throw an error but the partial data will still be accessible through error.data

import { graphql } from "@octokit/graphql";
graphql = graphql.defaults({
  headers: {
    authorization: `token secret123`,
  },
});
const query = `{
  repository(name: "probot", owner: "probot") {
    name
    ref(qualifiedName: "master") {
      target {
        ... on Commit {
          history(first: 25, after: "invalid cursor") {
            nodes {
              message
            }
          }
        }
      }
    }
  }
}`;

try {
  const result = await graphql(query);
} catch (error) {
  // server responds with
  // {
  //   "data": {
  //     "repository": {
  //       "name": "probot",
  //       "ref": null
  //     }
  //   },
  //   "errors": [
  //     {
  //       "type": "INVALID_CURSOR_ARGUMENTS",
  //       "path": [
  //         "repository",
  //         "ref",
  //         "target",
  //         "history"
  //       ],
  //       "locations": [
  //         {
  //           "line": 7,
  //           "column": 11
  //         }
  //       ],
  //       "message": "`invalid cursor` does not appear to be a valid cursor."
  //     }
  //   ]
  // }

  console.log("Request failed:", error.request); // { query, variables: {}, headers: { authorization: 'token secret123' } }
  console.log(error.message); // `invalid cursor` does not appear to be a valid cursor.
  console.log(error.data); // { repository: { name: 'probot', ref: null } }
}

Writing tests

You can pass a replacement for the built-in fetch implementation as request.fetch option. For example, using fetch-mock works great to write tests

import assert from "assert";
import fetchMock from "fetch-mock";

import { graphql } from "@octokit/graphql";

graphql("{ viewer { login } }", {
  headers: {
    authorization: "token secret123",
  },
  request: {
    fetch: fetchMock
      .sandbox()
      .post("https://api.github.com/graphql", (url, options) => {
        assert.strictEqual(options.headers.authorization, "token secret123");
        assert.strictEqual(
          options.body,
          '{"query":"{ viewer { login } }"}',
          "Sends correct query",
        );
        return { data: {} };
      }),
  },
});

License

MIT

@octokit/core@backstage/cligithub-actions-kitweb-node_upm-proxy-githubgithub-repo-fetchgithub-doc-server-lib@mestery/release-please@everything-registry/sub-chunk-676@larbish/github-module@khulnasoft-opensource/opengraph.khulnasoft.com@im-open/im-github-deployments@intuit-auto/core@luxass/projectrc@gitops-toolbox/github-toolsdx-scanner@mike-north/github-report@jlengstorf/gatsby-theme-showcase@jupiterone/graph-github@skynet1024/probot@silintl/vulnerability-scannerjabbar@outcome-co/verdaccio-github-authrgdrversions@opentr/cuttlecat@nuxtlabs/github-module@nuxtlabs/github-module-edgeevrgrn@omcs/request@npmcli/release-please@oselvar/connector-github@wmfs/lerna-syncuserfetchvercel-is-pull-requestttba11y-blamea11y-historyweekly-summary-typescripttina-graphqltina-graphql-primitives@telus/colophon-apptesting-bugsyhubgit@untile/github-changelog-generator@uphold/github-changelog-generatormaezato@zalando/roadblock@release-drafter/coregaudi-rankingskubastorybook-addon-github-issuesgithub-viewer-statsgithub-organization-automation-toolglue_opsgorgo-cli@security-alert/create-issue@security-alert/list-alerts@security-alert/sharerelease-pleaserelease-please-plusrename-repos@muukii/chglog_fetcher@narfeta/catalog-backendemoji-grassrepo-report@mktcodelib/good-first-web3-issuesfetch-github-tags@pkgjs/statusboardslack-github-issue-creator@pz-mxu/release-pleaseftl-release-pleasehocdoc-crawler-github@sudiptog81/awesome-cli@stoe/uebersicht-github-contibutions@rinse-repeat/actions-rs-coresponsorsme@roadiehq/backstage-plugin-security-insightsgitapi.itgithub-app-replgithub-cooldown-actiongithub-graphql-fetchergithub-graphql-v4-clientgithub-issue-cligithub-migration-monitorgithub-project-todo-mdgh-cmsgh-cms-qlgh-graphql-paginatorgh-project-migratorghdcgithub-sponsors-to-markdowngithub-user-statusgithub-sponsor-reportgithub_exporterhashnode-clihawk-fetch@monstrs/mctl-check@monstrs/mctl-legacy@monstrs/mctl-releaseset-gh-status
8.0.1

20 days ago

8.0.0-beta.1

23 days ago

8.0.0

23 days ago

7.0.0

9 months ago

7.0.2

6 months ago

7.0.1

8 months ago

6.0.0-beta.1

10 months ago

6.0.0-beta.2

9 months ago

5.0.6

10 months ago

6.0.1

9 months ago

6.0.0

9 months ago

5.0.5

1 year ago

5.0.4

1 year ago

5.0.3

1 year ago

5.0.2

1 year ago

2.3.0

1 year ago

5.0.1

2 years ago

5.0.0

2 years ago

4.8.0

3 years ago

4.7.0

3 years ago

4.6.3

3 years ago

4.6.4

3 years ago

4.6.2

3 years ago

4.6.1

3 years ago

4.6.0

3 years ago

4.5.9

3 years ago

4.5.8

3 years ago

4.5.7

3 years ago

4.5.6

4 years ago

4.5.5

4 years ago

4.5.4

4 years ago

4.5.3

4 years ago

4.5.2

4 years ago

4.5.1

4 years ago

4.5.0

4 years ago

4.4.1

4 years ago

4.4.0

4 years ago

4.3.1

4 years ago

4.3.0

4 years ago

4.2.2

4 years ago

4.2.1

4 years ago

4.2.0

5 years ago

4.1.0

5 years ago

4.0.1

5 years ago

4.0.0

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.1.3

5 years ago

2.1.2

5 years ago

2.1.1

5 years ago

2.1.0

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.0

5 years ago