gitlab.js•5.44 kB
import axios from 'axios';
export class GitLabService {
constructor(config) {
this.url = config.url;
this.token = config.token;
this.username = config.username;
if (!this.token) {
throw new Error('GitLab token is required');
}
this.api = axios.create({
baseURL: `${this.url}/api/v4`,
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
},
});
}
/**
* 获取用户在指定日期的提交记录
* @param {string} username - GitLab用户名
* @param {string} date - 日期,格式:YYYY-MM-DD
* @param {string} projectId - 项目ID(可选)
* @returns {Promise<Array>} 提交记录数组
*/
async getCommitsByDate(username, date, projectId = null) {
try {
const startDate = new Date(date);
const endDate = new Date(date);
endDate.setDate(endDate.getDate() + 1);
const since = startDate.toISOString();
const until = endDate.toISOString();
let commits = [];
if (projectId) {
// 查询指定项目的提交
commits = await this.getProjectCommits(projectId, username, since, until);
} else {
// 查询用户所有项目的提交
commits = await this.getAllUserCommits(username, since, until);
}
return commits;
} catch (error) {
console.error('获取GitLab提交记录失败:', error.message);
throw new Error(`获取GitLab提交记录失败: ${error.message}`);
}
}
/**
* 获取指定项目的提交记录
*/
async getProjectCommits(projectId, username, since, until) {
try {
const response = await this.api.get(`/projects/${projectId}/repository/commits`, {
params: {
author: username,
since: since,
until: until,
per_page: 100,
},
});
const project = await this.getProject(projectId);
return response.data.map(commit => ({
...commit,
project_id: projectId,
project_name: project.name,
project_path: project.path_with_namespace,
}));
} catch (error) {
console.error(`获取项目 ${projectId} 的提交记录失败:`, error.message);
return [];
}
}
/**
* 获取用户所有项目的提交记录
*/
async getAllUserCommits(username, since, until) {
try {
// 首先获取用户信息
const user = await this.getUser(username);
if (!user) {
throw new Error(`用户 ${username} 不存在`);
}
// 获取用户的所有项目
const projects = await this.getUserProjects(user.id);
const allCommits = [];
// 并发获取所有项目的提交记录
const commitPromises = projects.map(async (project) => {
try {
const commits = await this.getProjectCommits(project.id, username, since, until);
return commits;
} catch (error) {
console.error(`获取项目 ${project.name} 的提交记录失败:`, error.message);
return [];
}
});
const results = await Promise.all(commitPromises);
results.forEach(commits => allCommits.push(...commits));
// 按时间排序
return allCommits.sort((a, b) => new Date(b.committed_date) - new Date(a.committed_date));
} catch (error) {
console.error('获取用户所有提交记录失败:', error.message);
throw error;
}
}
/**
* 获取用户信息
*/
async getUser(username) {
try {
const response = await this.api.get(`/users`, {
params: {
username: username,
},
});
return response.data[0] || null;
} catch (error) {
console.error('获取用户信息失败:', error.message);
throw new Error(`获取用户信息失败: ${error.message}`);
}
}
/**
* 获取用户的项目列表
*/
async getUserProjects(userId) {
try {
const projects = [];
let page = 1;
const perPage = 100;
while (true) {
const response = await this.api.get(`/users/${userId}/projects`, {
params: {
page: page,
per_page: perPage,
simple: true,
membership: true,
},
});
if (response.data.length === 0) {
break;
}
projects.push(...response.data);
if (response.data.length < perPage) {
break;
}
page++;
}
return projects;
} catch (error) {
console.error('获取用户项目列表失败:', error.message);
throw new Error(`获取用户项目列表失败: ${error.message}`);
}
}
/**
* 获取项目信息
*/
async getProject(projectId) {
try {
const response = await this.api.get(`/projects/${projectId}`);
return response.data;
} catch (error) {
console.error('获取项目信息失败:', error.message);
throw new Error(`获取项目信息失败: ${error.message}`);
}
}
/**
* 测试GitLab连接
*/
async testConnection() {
try {
const response = await this.api.get('/user');
return {
success: true,
user: response.data,
message: '连接成功',
};
} catch (error) {
return {
success: false,
message: `连接失败: ${error.message}`,
};
}
}
}