Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Extendable client for GitHub's REST & GraphQL APIs

License

NotificationsYou must be signed in to change notification settings

octokit/core.js

Extendable client for GitHub's REST & GraphQL APIs

@latestBuild Status

If you need a minimalistic library to utilize GitHub'sREST API andGraphQL API which you can extend with plugins as needed, then@octokit/core is a great starting point.

If you don't need the Plugin API then using@octokit/request or@octokit/graphql directly is a good alternative.

Usage

BrowsersLoad@octokit/core directly fromesm.sh
<scripttype="module">import{Octokit}from"https://esm.sh/@octokit/core";</script>
Node

Install withnpm install @octokit/core

import{Octokit}from"@octokit/core";

As we useconditional exports, you will need to adapt yourtsconfig.json. See the TypeScript docs onpackage.json "exports".

REST API example

// Create a personal access token at https://github.com/settings/tokens/new?scopes=repoconstoctokit=newOctokit({auth:`personal-access-token123`});constresponse=awaitoctokit.request("GET /orgs/{org}/repos",{org:"octokit",type:"private",});

See@octokit/request for full documentation of the.request method.

GraphQL example

constoctokit=newOctokit({auth:`secret123`});constresponse=awaitoctokit.graphql(`query ($login: String!) {    organization(login: $login) {      repositories(privacy: PRIVATE) {        totalCount      }    }  }`,{login:"octokit"},);

See@octokit/graphql for full documentation of the.graphql method.

Options

name type description
options.authStrategyFunction Defaults to@octokit/auth-token. SeeAuthentication below for examples.
options.authString orObject SeeAuthentication below for examples.
options.baseUrlString

When using with GitHub Enterprise Server, setoptions.baseUrl to the root URL of the API. For example, if your GitHub Enterprise Server's hostname isgithub.acme-inc.com, then setoptions.baseUrl tohttps://github.acme-inc.com/api/v3. Example

constoctokit=newOctokit({baseUrl:"https://github.acme-inc.com/api/v3",});
options.previewsArray of Strings

Some REST API endpoints require preview headers to be set, or enableadditional features. Preview headers can be set on a per-request basis, e.g.

octokit.request("POST /repos/{owner}/{repo}/pulls",{mediaType:{previews:["shadow-cat"],},  owner,  repo,title:"My pull request",base:"main",head:"my-feature",draft:true,});

You can also set previews globally, by setting theoptions.previews option on the constructor. Example:

constoctokit=newOctokit({previews:["shadow-cat"],});
options.requestObject

Set a default request timeout (options.request.timeout) or anhttp(s).Agent e.g. for proxy usage (Node only,options.request.agent).

There are moreoptions.request.* options, see@octokit/request options.options.request can also be set on a per-request basis.

options.timeZoneString

Sets theTime-Zone header which defines a timezone according to thelist of names from the Olson database.

constoctokit=newOctokit({timeZone:"America/Los_Angeles",});

The time zone header will determine the timezone used for generating the timestamp when creating commits. SeeGitHub's Timezones documentation.

options.userAgentString

A custom user agent string for your app or library. Example

constoctokit=newOctokit({userAgent:"my-app/v1.2.3",});

Defaults

You can create a new Octokit class with customized default options.

constMyOctokit=Octokit.defaults({auth:"personal-access-token123",baseUrl:"https://github.acme-inc.com/api/v3",userAgent:"my-app/v1.2.3",});constoctokit1=newMyOctokit();constoctokit2=newMyOctokit();

If you pass additional options to your new constructor, the options will be merged shallowly.

constMyOctokit=Octokit.defaults({foo:{opt1:1,},});constoctokit=newMyOctokit({foo:{opt2:1,},});// options will be { foo: { opt2: 1 }}

If you need a deep or conditional merge, you can pass a function instead.

constMyOctokit=Octokit.defaults((options)=>{return{foo:Object.assign({},options.foo,{opt1:1}),};});constoctokit=newMyOctokit({foo:{opt2:1},});// options will be { foo: { opt1: 1, opt2: 1 }}

Be careful about mutating theoptions object in theOctokit.defaults callback, as it can have unforeseen consequences.

Authentication

Authentication is optional for some REST API endpoints accessing public data, but is required for GraphQL queries. Using authentication also increases yourAPI rate limit.

By default, Octokit authenticates using thetoken authentication strategy. Pass in a token usingoptions.auth. It can be a personal access token, an OAuth token, an installation access token or a JSON Web Token for GitHub App authentication. TheAuthorization header will be set according to the type of token.

import{Octokit}from"@octokit/core";constoctokit=newOctokit({auth:"mypersonalaccesstoken123",});const{ data}=awaitoctokit.request("/user");

To use a different authentication strategy, setoptions.authStrategy. A list of authentication strategies is available atoctokit/authentication-strategies.js.

Example

import{Octokit}from"@octokit/core";import{createAppAuth}from"@octokit/auth-app";constappOctokit=newOctokit({authStrategy:createAppAuth,auth:{appId:123,privateKey:process.env.PRIVATE_KEY,},});const{ data}=awaitappOctokit.request("/app");

The.auth() method returned by the current authentication strategy can be accessed atoctokit.auth(). Example

const{ token}=awaitappOctokit.auth({type:"installation",installationId:123,});

Logging

There are four built-in log methods

  1. octokit.log.debug(message[, additionalInfo])
  2. octokit.log.info(message[, additionalInfo])
  3. octokit.log.warn(message[, additionalInfo])
  4. octokit.log.error(message[, additionalInfo])

They can be configured using thelog client option. By default,octokit.log.debug() andoctokit.log.info() are no-ops, while the other two callconsole.warn() andconsole.error() respectively.

This is useful if you build reusableplugins.

If you would like to make the log level configurable using an environment variable or external option, we recommend theconsole-log-level package. Example

importconsoleLogLevelfrom"console-log-level";constoctokit=newOctokit({log:consoleLogLevel({level:"info"}),});

Hooks

You can customize Octokit's request lifecycle with hooks.

octokit.hook.before("request",async(options)=>{validate(options);});octokit.hook.after("request",async(response,options)=>{console.log(`${options.method}${options.url}:${response.status}`);});octokit.hook.error("request",async(error,options)=>{if(error.status===304){returnfindInCache(error.response.headers.etag);}throwerror;});octokit.hook.wrap("request",async(request,options)=>{// add logic before, after, catch errors or replace the request altogetherreturnrequest(options);});

See before-after-hook for more documentation on hooks.

Plugins

Octokit’s functionality can be extended using plugins. TheOctokit.plugin() method accepts a plugin (or many) and returns a new constructor.

A plugin is a function which gets two arguments:

  1. the current instance
  2. the options passed to the constructor.

In order to extendoctokit's API, the plugin must return an object with the new methods. Please refrain from adding methods directly to theoctokit instance, especialy if you depend on keys that do not exist in@octokit/core, such asoctokit.rest.

// index.jsimport{Octokit}from"@octokit/core";importmyPluginfrom"./lib/my-plugin.js";importoctokitPluginExamplefrom"octokit-plugin-example";constMyOctokit=Octokit.plugin(myPlugin,octokitPluginExample);constoctokit=newMyOctokit({greeting:"Moin moin"});octokit.helloWorld();// logs "Moin moin, world!"octokit.request("GET /");// logs "GET / - 200 in 123ms"// lib/my-plugin.jsconstplugin=(octokit,options={greeting:"Hello"})=>{// hook into the request lifecycleoctokit.hook.wrap("request",async(request,options)=>{consttime=Date.now();constresponse=awaitrequest(options);console.log(`${options.method}${options.url}${response.status} in${Date.now()-time}ms`);returnresponse;});// add a custom methodreturn{helloWorld:()=>console.log(`${options.greeting}, world!`);}};exportdefaultplugin;

Build your own Octokit with Plugins and Defaults

You can build your own Octokit class with preset default options and plugins. In fact, this is mostly how the@octokit/<context> modules work, such as@octokit/action:

import{Octokit}from"@octokit/core";import{paginateRest}from"@octokit/plugin-paginate-rest";import{throttling}from"@octokit/plugin-throttling";import{retry}from"@octokit/plugin-retry";import{createActionAuth}from"@octokit/auth-action";constMyActionOctokit=Octokit.plugin(paginateRest,throttling,retry,).defaults({throttle:{onAbuseLimit:(retryAfter,options)=>{/* ... */},onRateLimit:(retryAfter,options)=>{/* ... */},},authStrategy:createActionAuth,userAgent:`my-octokit-action/v1.2.3`,});constoctokit=newMyActionOctokit();constinstallations=awaitoctokit.paginate("GET /app/installations");

LICENSE

MIT


[8]ページ先頭

©2009-2025 Movatter.jp