octokit/core.js
Được TopGit lập chỉ mục từ metadata GitHub: octokit/core.js có 1.3k sao, viết chủ yếu bằng TypeScript. Extendable client for GitHub's REST & GraphQL APIs
Tóm tắt dựng từ metadata GitHub của chính dự án — chưa có bài review TopGit. Trang sẽ tự động cập nhật khi bài review đầy đủ được xuất bản.
TopGit viết bài đầy đủ cho repo có nhiều sao nhất và được yêu cầu nhiều nhất. Trang này là snapshot trong thời gian chờ — xem README gốc ở tab READ ME.
Snapshot
Cộng tác viên hàng đầu
Xem cộng tác viên hàng đầu
core.js
Extendable client for GitHub's REST & GraphQL APIs
- Usage
- REST API example
- GraphQL example
- Options
- Defaults
- Authentication
- Logging
- Hooks
- Plugins
- Build your own Octokit with Plugins and Defaults
- LICENSE
If you need a minimalistic library to utilize GitHub's REST API and GraphQL 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
| Browsers |
Load @octokit/core directly from esm.sh
|
|---|---|
| Node |
Install with
|
As we use conditional exports, you will need to adapt your tsconfig.json. See the TypeScript docs on package.json "exports".
REST API example
// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo
const octokit = new Octokit({ auth: `personal-access-token123` });
const response = await octokit.request("GET /orgs/{org}/repos", {
org: "octokit",
type: "private",
});
See @octokit/request for full documentation of the .request method.
GraphQL example
const octokit = new Octokit({ auth: `secret123` });
const response = await octokit.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.authStrategy
|
Function |
Defaults to @octokit/auth-token. See Authentication below for examples.
|
options.auth
|
String or Object
| See Authentication below for examples. |
options.baseUrl
|
String
|
When using with GitHub Enterprise Server, set
|
options.previews
|
Array of Strings
|
Some REST API endpoints require preview headers to be set, or enable additional features. Preview headers can be set on a per-request basis, e.g.
You can also set previews globally, by setting the
|
options.request
|
Object
|
Set a default request timeout ( There are more |
options.timeZone
|
String
|
Sets the
The time zone header will determine the timezone used for generating the timestamp when creating commits. See GitHub's Timezones documentation. |
options.userAgent
|
String
|
A custom user agent string for your app or library. Example
|
Defaults
You can create a new Octokit class with customized default options.
const MyOctokit = Octokit.defaults({
auth: "personal-access-token123",
baseUrl: "https://github.acme-inc.com/api/v3",
userAgent: "my-app/v1.2.3",
});
const octokit1 = new MyOctokit();
const octokit2 = new MyOctokit();
If you pass additional options to your new constructor, the options will be merged shallowly.
const MyOctokit = Octokit.defaults({
foo: {
opt1: 1,
},
});
const octokit = new MyOctokit({
foo: {
opt2: 1,
},
});
// options will be { foo: { opt2: 1 }}
If you need a deep or conditional merge, you can pass a function instead.
const MyOctokit = Octokit.defaults((options) => {
return {
foo: Object.assign({}, options.foo, { opt1: 1 }),
};
});
const octokit = new MyOctokit({
foo: { opt2: 1 },
});
// options will be { foo: { opt1: 1, opt2: 1 }}
Be careful about mutating the options object in the Octokit.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 your API rate limit.
By default, Octokit authenticates using the token authentication strategy. Pass in a token using options.auth. It can be a personal access token, an OAuth token, an installation access token or a JSON Web Token for GitHub App authentication. The Authorization header will be set according to the type of token.
import { Octokit } from "@octokit/core";
const octokit = new Octokit({
auth: "mypersonalaccesstoken123",
});
const { data } = await octokit.request("/user");
To use a different authentication strategy, set options.authStrategy. A list of authentication strategies is available at octokit/authentication-strategies.js.
Example
import { Octokit } from "@octokit/core";
import { createAppAuth } from "@octokit/auth-app";
const appOctokit = new Octokit({
authStrategy: createAppAuth,
auth: {
appId: 123,
privateKey: process.env.PRIVATE_KEY,
},
});
const { data } = await appOctokit.request("/app");
The .auth() method returned by the current authentication strategy can be accessed at octokit.auth(). Example
const { token } = await appOctokit.auth({
type: "installation",
installationId: 123,
});
Logging
There are four built-in log methods
octokit.log.debug(message[, additionalInfo])octokit.log.info(message[, additionalInfo])octokit.log.warn(message[, additionalInfo])octokit.log.error(message[, additionalInfo])
They can be configured using the log client option. By default, octokit.log.debug() and octokit.log.info() are no-ops, while the other two call console.warn() and console.error() respectively.
This is useful if you build reusable plugins.
If you would like to make the log level configurable using an environment variable or external option, we recommend the console-log-level package. Example
import consoleLogLevel from "console-log-level";
const octokit = new Octokit({
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) {
return findInCache(error.response.headers.etag);
}
throw error;
});
octokit.hook.wrap("request", async (request, options) => {
// add logic before, after, catch errors or replace the request altogether
return request(options);
});
See before-after-hook for more documentation on hooks.
Plugins
Octokit’s functionality can be extended using plugins. The Octokit.plugin() method accepts a plugin (or many) and returns a new constructor.
A plugin is a function which gets two arguments:
- the current instance
- the options passed to the constructor.
In order to extend octokit's API, the plugin must return an object with the new methods. Please refrain from adding methods directly to the octokit instance, especialy if you depend on keys that do not exist in @octokit/core, such as octokit.rest.
// index.js
import { Octokit } from "@octokit/core";
import myPlugin from "./lib/my-plugin.js";
import octokitPluginExample from "octokit-plugin-example";
const MyOctokit = Octokit.plugin(
myPlugin,
octokitPluginExample
);
const octokit = new MyOctokit({ greeting: "Moin moin" });
octokit.helloWorld(); // logs "Moin moin, world!"
octokit.request("GET /"); // logs "GET / - 200 in 123ms"
// lib/my-plugin.js
const plugin = (octokit, options = { greeting: "Hello" }) => {
// hook into the request lifecycle
octokit.hook.wrap("request", async (request, options) => {
const time = Date.now();
const response = await request(options);
console.log(
`${options.method} ${options.url} – ${response.status} in ${Date.now() -
time}ms`
);
return response;
});
// add a custom method
return {
helloWorld: () => console.log(`${options.greeting}, world!`);
}
};
export default plugin;
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";
const MyActionOctokit = Octokit.plugin(
paginateRest,
throttling,
retry,
).defaults({
throttle: {
onAbuseLimit: (retryAfter, options) => {
/* ... */
},
onRateLimit: (retryAfter, options) => {
/* ... */
},
},
authStrategy: createActionAuth,
userAgent: `my-octokit-action/v1.2.3`,
});
const octokit = new MyActionOctokit();
const installations = await octokit.paginate("GET /app/installations");
LICENSE
MIT
Repo liên quan
:books: Freely available programming books
All Algorithms implemented in Python
A curated list of awesome Go frameworks, libraries and software
Master programming by recreating your favorite technologies from scratch.
Trả lời nhanh
Đọc thêm về octokit/core.js ở đâu?
Trang TopGit này là một snapshot — tab "Readme" hiển thị nguyên văn README của repo (đã bỏ link, giữ ảnh). Repo GitHub ở github.com/octokit/core.js là nguồn chính thức.
octokit/core.js có phải mã nguồn mở không?
Có — octokit/core.js phát hành theo license MIT, nghĩa là mã nguồn mở để đọc, fork và (tùy license) tái sử dụng. Mã: github.com/octokit/core.js.
octokit/core.js là gì?
octokit/core.js (octokit/core.js) là dự án TypeScript trên GitHub. Theo mô tả gốc: Extendable client for GitHub's REST & GraphQL APIs
Đọc đầy đủ README ở tab phía trên.
Chưa chắc core.js có hợp với bạn?
Để ChatGPT, Claude hoặc Perplexity tìm hiểu giúp — bấm bên dưới và xem AI nói gì về core.js.