You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于JS与GraphQL构建GitHub Workflow完整示例

GitHub Workflow中使用JavaScript调用GitHub GraphQL Mutations的完整示例

1. Workflow配置文件(.github/workflows/graphql-mutation.yml)

定义Workflow的触发条件、运行环境与执行步骤:

name: GraphQL Mutation Workflow

on:
  push:
    branches: [ main ]

jobs:
  run-graphql-mutation:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm install node-fetch@3

      - name: Run GraphQL mutation script
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          REPO_OWNER: ${{ github.repository_owner }}
          REPO_NAME: ${{ github.event.repository.name }}
        run: node ./scripts/run-graphql-mutation.js

2. JavaScript脚本文件(./scripts/run-graphql-mutation.js)

实现GraphQL请求构造、mutation发送与响应处理,示例为创建新Issue的逻辑,可替换为你需要的mutation:

import fetch from 'node-fetch';

async function runGraphQLMutation() {
  // 从环境变量读取必要参数
  const token = process.env.GITHUB_TOKEN;
  const repoOwner = process.env.REPO_OWNER;
  const repoName = process.env.REPO_NAME;

  if (!token || !repoOwner || !repoName) {
    console.error('缺失必要环境变量');
    process.exit(1);
  }

  // 定义GraphQL Mutation
  const mutation = `
    mutation CreateIssue($owner: String!, $repo: String!, $title: String!, $body: String!) {
      createIssue(input: {repositoryId: "", owner: $owner, name: $repo, title: $title, body: $body}) {
        issue {
          number
          title
        }
      }
    }
  `;

  // 配置mutation所需变量
  const variables = {
    owner: repoOwner,
    repo: repoName,
    title: '通过GraphQL Mutation自动创建的Issue',
    body: '此Issue由GitHub Workflow调用GraphQL接口生成'
  };

  try {
    const response = await fetch('https://api.github.com/graphql', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ query: mutation, variables })
    });

    const result = await response.json();

    if (result.errors) {
      console.error('GraphQL请求错误:', result.errors);
      process.exit(1);
    }

    console.log('Mutation执行成功!创建的Issue:', result.data.createIssue.issue);
  } catch (error) {
    console.error('请求失败:', error);
    process.exit(1);
  }
}

runGraphQLMutation();

3. 关键注意事项

  • 权限配置:默认secrets.GITHUB_TOKEN仅拥有当前仓库的基础权限,若你的mutation需要更高权限(如修改仓库设置、管理团队),需生成Personal Access Token(PAT)并添加到仓库secrets中,替换secrets.GITHUB_TOKEN。
  • Mutation替换:将示例中的CreateIssue mutation替换为目标操作,比如updateRepository、addLabelToLabelable等,具体可参考GitHub GraphQL官方文档的mutation列表。
  • 变量适配:根据实际需求调整脚本中的变量参数,确保与mutation定义匹配。

内容的提问来源于stack exchange,提问作者Vipin Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:20:02