All Projects → octokit → Graphql.js

octokit / Graphql.js

Licence: mit
GitHub GraphQL API client for browsers and Node

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Graphql.js

Noice
A native Android app to relax, improve focus and boost productivity with minimal background noise.
Stars: ✭ 264 (-1.49%)
Mutual labels:  hacktoberfest
Deepchem
Democratizing Deep-Learning for Drug Discovery, Quantum Chemistry, Materials Science and Biology
Stars: ✭ 3,324 (+1140.3%)
Mutual labels:  hacktoberfest
Alphavantage
A simple interface to the Alpha Vantage API.
Stars: ✭ 266 (-0.75%)
Mutual labels:  hacktoberfest
Ac Music Extension
Google Chrome extension that plays hourly Animal Crossing music and more while browsing!
Stars: ✭ 262 (-2.24%)
Mutual labels:  hacktoberfest
Fl chart
A powerful Flutter chart library, currently supporting Line Chart, Bar Chart, Pie Chart, Scatter Chart and Radar Chart.
Stars: ✭ 3,882 (+1348.51%)
Mutual labels:  hacktoberfest
Cpp
Repository for C++/C codes and algos.
Stars: ✭ 265 (-1.12%)
Mutual labels:  hacktoberfest
Javascript Cheatsheet
Basic Javascript Cheat Sheet
Stars: ✭ 262 (-2.24%)
Mutual labels:  hacktoberfest
First Born
Component library for React Native
Stars: ✭ 267 (-0.37%)
Mutual labels:  hacktoberfest
Wp Graphql
🚀 GraphQL API for WordPress
Stars: ✭ 3,097 (+1055.6%)
Mutual labels:  hacktoberfest
Free Pmo
Project management software for freelancers or agencies, built with Laravel 5.
Stars: ✭ 264 (-1.49%)
Mutual labels:  hacktoberfest
Community.general
Ansible Community General Collection
Stars: ✭ 266 (-0.75%)
Mutual labels:  hacktoberfest
Termonad
Terminal emulator configurable in Haskell.
Stars: ✭ 266 (-0.75%)
Mutual labels:  hacktoberfest
Toha
A Hugo theme for personal portfolio
Stars: ✭ 267 (-0.37%)
Mutual labels:  hacktoberfest
Commands
Java Command Dispatch Framework - (Bukkit, Spigot, Paper, Sponge, Bungee, JDA, Velocity supported, generically usable anywhere)
Stars: ✭ 266 (-0.75%)
Mutual labels:  hacktoberfest
Node Red Docker
Repository for all things Node-RED and Docker related
Stars: ✭ 267 (-0.37%)
Mutual labels:  hacktoberfest
Foremast
Spinnaker Pipeline/Infrastructure Configuration and Templating Tool - Pipelines as Code.
Stars: ✭ 263 (-1.87%)
Mutual labels:  hacktoberfest
Ultimate Python
Ultimate Python study guide for newcomers and professionals alike. 🐍 🐍 🐍
Stars: ✭ 3,309 (+1134.7%)
Mutual labels:  hacktoberfest
Vscode Home Assistant
Visual Studio Code Extension for Home Assistant. ⭐ if you think this is cool!
Stars: ✭ 267 (-0.37%)
Mutual labels:  hacktoberfest
Kinto.js
An Offline-First JavaScript Client for Kinto.
Stars: ✭ 268 (+0%)
Mutual labels:  hacktoberfest
Auth.js
GitHub API authentication library for JavaScript and Node.js
Stars: ✭ 267 (-0.37%)
Mutual labels:  hacktoberfest

graphql.js

GitHub GraphQL API client for browsers and Node

@latest Build Status

Usage

Browsers

Load @octokit/graphql directly from cdn.skypack.dev

<script type="module">
  import { graphql } from "https://cdn.skypack.dev/@octokit/graphql";
</script>
Node

Install with npm install @octokit/graphql

const { graphql } = require("@octokit/graphql");
// or: 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 } = require("@octokit/auth-app");
const auth = createAppAuth({
  id: 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 { lastIssues } = 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

const { graphql } = require("@octokit/graphql");
const { lastIssues } = 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

let { graphql } = require("@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

const { request } = require("@octokit/request");
const { withCustomRequest } = require("@octokit/graphql");

let requestCounter = 0;
const myRequest = request.defaults({
  headers: {
    authentication: "token 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 the first error from the response’s errors array. All errors can be accessed at error.errors. error.request has the request options such as query, variables and headers set for easier debugging.

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

try {
  const result = await graphql(query);
} catch (error) {
  // server responds with
  // {
  //  "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'
}

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

let { graphql } = require("@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

const assert = require("assert");
const fetchMock = require("fetch-mock/es5/server");

const { graphql } = require("@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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].