octokit.js

2024-04-18 09:23:52 浏览数 (2)

暴食杀人多于利剑杀人。——伯里兹

分享一个框架封装了GitHubAPI调用

GitHub - octokit/octokit.js: The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.

等于是一个SDK

目前,GitHub 维护以下语言/框架/平台的 SDK:

  • JavaScript / TypeScript
  • C# / .NET
  • Ruby
  • Terraform provider

还有 2 个 SDK,它们是根据 GitHub 的 OpenAPI 描述生成的!

  • C# / .NET
  • Go

浏览器里安装:

代码语言:javascript复制
<script type="module">
import { Octokit, App } from "https://esm.sh/octokit";
</script>

示例:获取经过身份验证的用户的用户名。

代码语言:javascript复制
// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo
const octokit = new Octokit({ auth: `personal-access-token123` });

// Compare: https://docs.github.com/en/rest/reference/users#get-the-authenticated-user
const {
  data: { login },
} = await octokit.rest.users.getAuthenticated();
console.log("Hello, %s", login);

这里支持两种方式,就拿创建issues举例

代码语言:javascript复制
await octokit.rest.issues.create({
  owner: "octocat",
  repo: "hello-world",
  title: "Hello, world!",
  body: "I created this issue using Octokit!",
});

和下面的方式相同

代码语言:javascript复制
await octokit.request("POST /repos/{owner}/{repo}/issues", {
  owner: "octocat",
  repo: "hello-world",
  title: "Hello, world!",
  body: "I created this issue using Octokit!",
});

还有分页查询仓库里的issues

代码语言:javascript复制
const iterator = octokit.paginate.iterator(octokit.rest.issues.listForRepo, {
  owner: "octocat",
  repo: "hello-world",
  per_page: 100,
});

// iterate through each response
for await (const { data: issues } of iterator) {
  for (const issue of issues) {
    console.log("Issue #%d: %s", issue.number, issue.title);
  }
}

还可以使用异步的方式去做

代码语言:javascript复制
const issues = await octokit.paginate(octokit.rest.issues.listForRepo, {
  owner: "octocat",
  repo: "hello-world",
  per_page: 100,
});

设置媒体格式:

代码语言:javascript复制
const { data } = await octokit.rest.repos.getContent({
  mediaType: {
    format: "raw",
  },
  owner: "octocat",
  repo: "hello-world",
  path: "package.json",
});
console.log("package name: %s", JSON.parse(data).name);

错误处理

代码语言:javascript复制
import { RequestError } from "octokit";
代码语言:javascript复制
try {
  // your code here that sends at least one Octokit request
  await octokit.request("GET /");
} catch (error) {
  // Octokit errors are instances of RequestError, so they always have an `error.status` property containing the HTTP response code.
  if (error instanceof RequestError) {
    // handle Octokit error
    // error.message; // Oops
    // error.status; // 500
    // error.request; // { method, url, headers, body }
    // error.response; // { url, status, headers, data }
  } else {
    // handle all other errors
    throw error;
  }
}

也有GraphQL的支持,例如获取经过身份验证的用户的登录信息

代码语言:javascript复制
const {
  viewer: { login },
} = await octokit.graphql(`{
  viewer {
    login
  }
}`);

可以把变量放到第二个参数传进去

代码语言:javascript复制
const { lastIssues } = await octokit.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",
  },
);

关于GraphQL的分页查询仓库的issues

代码语言:javascript复制
const { allIssues } = await octokit.graphql.paginate(
  `
    query allIssues($owner: String!, $repo: String!, $num: Int = 10, $cursor: String) {
      repository(owner: $owner, name: $repo) {
        issues(first: $num, after: $cursor) {
          edges {
            node {
              title
            }
          }
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    }
  `,
  {
    owner: "octokit",
    repo: "graphql.js",
  },
);

创建Label

代码语言:javascript复制
await octokit.graphql(
  `mutation createLabel($repositoryId:ID!,name:String!,color:String!) {
  createLabel(input:{repositoryId:$repositoryId,name:$name}) {
    label: {
      id
    }
  }
}`,
  {
    repositoryId: 1,
    name: "important",
    color: "cc0000",
    mediaType: {
      previews: ["bane"],
    },
  },
);

0 人点赞