- Notifications
You must be signed in to change notification settings - Fork87
GitHub GraphQL API client for browsers and Node
License
octokit/graphql.js
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
GitHub GraphQL API client for browsers and Node
Browsers | Load <scripttype="module">import{graphql}from"https://esm.sh/@octokit/graphql";</script> |
---|---|
Node | Install with import{graphql}from"@octokit/graphql"; |
const{ repository}=awaitgraphql(` { repository(owner: "octokit", name: "graphql.js") { issues(last: 3) { edges { node { title } } } } } `,{headers:{authorization:`token secret123`,},},);
The simplest way to authenticate a request is to set theAuthorization
header, e.g. to apersonal access token.
constgraphqlWithAuth=graphql.defaults({headers:{authorization:`token secret123`,},});const{ repository}=awaitgraphqlWithAuth(` { 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}=awaitimport("@octokit/auth-app");constauth=createAppAuth({appId:process.env.APP_ID,privateKey:process.env.PRIVATE_KEY,installationId:123,});constgraphqlWithAuth=graphql.defaults({request:{hook:auth.hook,},});const{ repository}=awaitgraphqlWithAuth(`{ repository(owner: "octokit", name: "graphql.js") { issues(last: 3) { edges { node { title } } } } }`,);
const{ repository}=awaitgraphql(` 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`,},},);
import{graphql}from("@octokit/graphql");const{ repository}=awaitgraphql({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`,},});
import{graphql}from"@octokit/graphql";graphql=graphql.defaults({baseUrl:"https://github-enterprise.acme-inc.com/api",headers:{authorization:`token secret123`,},});const{ repository}=awaitgraphql(` { repository(owner: "acme-project", name: "acme-repo") { issues(last: 3) { edges { node { title } } } } }`);
import{request}from"@octokit/request";import{withCustomRequest}from"@octokit/graphql";letrequestCounter=0;constmyRequest=request.defaults({headers:{authorization:"bearer secret123",},request:{hook(request,options){requestCounter++;returnrequest(options);},},});constmyGraphql=withCustomRequest(myRequest);awaitrequest("/");awaitmyGraphql(` { repository(owner: "acme-project", name: "acme-repo") { issues(last: 3) { edges { node { title } } } } }`);// requestCounter is now 2
@octokit/graphql
is exposing proper types for its usage with TypeScript projects.
Additionally,GraphQlQueryResponseData
has been exposed to users:
importtype{GraphQlQueryResponseData}from"@octokit/graphql";
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 aterror.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`,},});constquery=`{ viewer { bioHtml }}`;try{constresult=awaitgraphql(query);}catch(error){if(errorinstanceofGraphqlResponseError){// 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}}
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 througherror.data
import{graphql}from"@octokit/graphql";graphql=graphql.defaults({headers:{authorization:`token secret123`,},});constquery=`{ repository(name: "probot", owner: "probot") { name ref(qualifiedName: "master") { target { ... on Commit { history(first: 25, after: "invalid cursor") { nodes { message } } } } } }}`;try{constresult=awaitgraphql(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 }}}
You can pass a replacement forthe built-in fetch implementation asrequest.fetch
option. For example, usingfetch-mock works great to write tests
importassertfrom"assert";importfetchMockfrom"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:{}};}),},});
About
GitHub GraphQL API client for browsers and Node
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.