Node.js操作GitLab API指南

1,209 阅读2分钟

背景

之所以写这篇文章,是因为前段时间在实现云函数平台的过程中,因需要将应用的云函数代码同步到Gitlab平台,由于云函数平台是以nodejs代码实现的,所以研究了一下node如何调用Gitlab的Open API操作gitlab代码仓库,特此将自己的一些经验分享给大家。

操作方式

关于node操作gitlab api的形式有两种方式:

1.直接通过axios库或者curl命令发起http请求;

curl --request GET "https://gitlab.example.com/api/v4/projects"

2.通过使用gitlab官方提供的npm库来操作:@gitbeaker/rest(推荐

npm i @gitbeaker/rest

常用API介绍

准备工作:

Gitlab API 官方文档地址:docs.gitlab.com/ee/api/proj…

1.在开始调用之前需要做些准备工作:我们必须得有一个访问Token才能调用API,在gitlab上创建好之后保存下来就可以了。

image.png

2.接下来我们得先创建一个gitlab实例:

import { Gitlab } from '@gitbeaker/rest';

const gitlab = new Gitlab({
  host: 'http://example.com',
  token: 'personaltoken',
});

创建一个代码仓库

async function createProject() {
  const res = await gitlab.Projects.create({
    name: 'xxxx', //项目名称,必填
    description: 'New Project',
    namespace_id: '你自己在Gitlab上的组ID',
    visibility: 'private', //默认是私有项目,值有“private”和“public”
    initialize_with_readme: true, //是否自动创建一个readme文件
  }).catch(error => {
    console.error('项目创建失败:', error);
  });
  return res.id;
}

image.png

创建一个代码文件

async function createNewFile() {
  const projectId = '项目ID';
  const filePath = 'test.ts';//文件路径
  const branch = 'master'; //分支名称
  const content = 'console.log("Hello, World!");'; //文件内容
  const commitMessage = 'Add test.ts'; //提交信息
  
  const res = await gitlab.RepositoryFiles.create(
    projectId,
    filePath,
    branch,
    content,
    commitMessage,
  ).catch((error) => {
    console.error("添加文件失败:", error);
  });
  return res;
}

编辑代码文件

async function updateFile() {
  const projectId = '项目ID';
  const filePath = 'test.ts';//文件路径
  const branch = 'master'; //分支名称
  const content = 'console.log("Hello, World!");--------更新内容------------'; //文件内容
  const commitMessage = 'Update test.ts'; //提交信息

  const res = await gitlab.RepositoryFiles.edit(
    projectId,
    filePath,
    branch,
    content,
    commitMessage,
  ).catch((error) => {
    console.error("更新文件代码失败:", error);
  });
  return res;
}

删除文件

async function deleteFile() {
  return gitlab.RepositoryFiles.remove(
    projectId,
    filePath,
    branch,
    commitMessage
  ).catch((error) => {
    console.error("删除文件代码失败:", error);
  });
}

提交一个commit

async function commit() {
  const actions = [
    {
      "action": "create",// 创建一个文件
      "filePath": 'a.ts',
      "content": 'console.log("Hello, World!");'
    },
    {
      "action": "delete",// 删除一个文件
      "filePath": 'b.ts'
    },
  ]
  return gitlab.Commits.create(
    projectId,
    branch,
    message,
    actions
  ).catch((error) => {
    console.error("Commit提交失败:", error);
  });
}

这里主要参数在于actions,它是一个数组,元素是一个对象,包括以下这些属性:

image.png