feat: 更新GitLab API调用方法
All checks were successful
CI Monitor CI/CD / build-image (push) Successful in 28s
CI Monitor CI/CD / deploy (push) Successful in 28s

This commit is contained in:
zhaoyingbo 2024-07-01 12:33:40 +00:00
parent ea389da7bb
commit 71461a04df
7 changed files with 230 additions and 107 deletions

View File

@ -19,7 +19,10 @@ const getFullPipelineList = async (project: ProjectRecordModel) => {
let page = 1;
let hasBeforeLatestTime = false;
while (!hasBeforeLatestTime) {
const pipelines = await service.fetchPipelines(project.project_id, page++);
const pipelines = await service.gitlab.fetchPipelines(
project.project_id,
page++
);
// 如果当前页没有数据,则直接跳出
if (pipelines.length === 0) break;
pipelines.forEach((pipeline) => {
@ -32,7 +35,7 @@ const getFullPipelineList = async (project: ProjectRecordModel) => {
}
const fullPipelineDetailList = await Promise.all(
fullPipelineList.map(({ project_id, id, created_at }) =>
service.fetchPipelineDetails(project_id, id, created_at)
service.gitlab.fetchPipelineDetails(project_id, id, created_at)
)
);
return fullPipelineDetailList.filter(

View File

@ -6,7 +6,9 @@ import service from "../../service";
*
*/
const fillProj = async (project: ProjectRecordModel) => {
const projDetail = await service.fetchProjectDetails(project.project_id);
const projDetail = await service.gitlab.fetchProjectDetails(
project.project_id
);
if (!projDetail) {
return project;
}

View File

@ -121,7 +121,7 @@ const getRobotMsg = async () =>
* @param chat_id
*/
const sendCIReportByChatId = async (chat_id: string) => {
await service.sendMessage.byChatId(chat_id, await getRobotMsg());
await service.egg.sendMessage.byChatId(chat_id, await getRobotMsg());
};
/**
@ -129,7 +129,10 @@ const sendCIReportByChatId = async (chat_id: string) => {
* @returns
*/
const sendCIReportByCron = async () =>
await service.sendMessage.byGroupId("52usf3w8l6z4vs1", await getRobotMsg());
await service.egg.sendMessage.byGroupId(
"52usf3w8l6z4vs1",
await getRobotMsg()
);
const manageRobot = {
sendCIReportByChatId,

34
service/egg.ts Normal file
View File

@ -0,0 +1,34 @@
import netTool from "./netTool";
const sendMessage = async (body: any) => {
const URL = "https://egg.imoaix.cn/message";
try {
const res = await netTool.post(URL, JSON.stringify(body));
return res;
} catch {
return null;
}
};
sendMessage.byGroupId = async (group_id: string, content: string) => {
return sendMessage({
group_id,
msg_type: "interactive",
content,
});
};
sendMessage.byChatId = async (chat_id: string, content: string) => {
return sendMessage({
receive_id: chat_id,
receive_id_type: "chat_id",
msg_type: "interactive",
content,
});
};
const egg = {
sendMessage,
};
export default egg;

81
service/gitlab.ts Normal file
View File

@ -0,0 +1,81 @@
import netTool from "./netTool";
const AUTH_HEADER = { "PRIVATE-TOKEN": "Zd1UASPcMwVox5tNS6ep" };
const BASE_URL = "https://git.n.xiaomi.com/api/v4";
/**
*
* @param id
* @returns
*/
const fetchProjectDetails = async (id: number) => {
const URL = `${BASE_URL}/projects/${id}`;
try {
const response = (await netTool.get(
URL,
{},
AUTH_HEADER
)) as GitlabProjDetail & GitlabError;
if (response.message === "404 Project Not Found") return null;
return response;
} catch {
return null;
}
};
/**
* 线
* @param project_id
* @param page
* @returns
*/
const fetchPipelines = async (project_id: number, page = 1) => {
const URL = `${BASE_URL}/projects/${project_id}/pipelines`;
const params = { scope: "finished", per_page: 100, page };
try {
const response = (await netTool.get(
URL,
params,
AUTH_HEADER
)) as GitlabPipeline[] & GitlabError;
if (response?.message === "404 Project Not Found") return [];
return response;
} catch {
return [] as GitlabPipeline[];
}
};
/**
* 线
* @param project_id
* @param pipeline_id
* @param created_at
* @returns
*/
const fetchPipelineDetails = async (
project_id: number,
pipeline_id: number,
created_at: string
) => {
const URL = `${BASE_URL}/projects/${project_id}/pipelines/${pipeline_id}`;
try {
const response = (await netTool.get(
URL,
{},
AUTH_HEADER
)) as GitlabPipelineDetail & GitlabError;
if (response.message === "404 Project Not Found") return null;
return { ...response, created_at };
} catch {
return null;
}
};
const gitlab = {
fetchProjectDetails,
fetchPipelines,
fetchPipelineDetails,
};
export default gitlab;

View File

@ -1,107 +1,9 @@
const fetchGetParams = {
method: "GET",
headers: { "PRIVATE-TOKEN": "Zd1UASPcMwVox5tNS6ep" },
};
/**
*
* @param id id
*/
const fetchProjectDetails = async (id: number) => {
try {
const response = await fetch(
`https://git.n.xiaomi.com/api/v4/projects/${id}`,
fetchGetParams
);
const body = (await response.json()) as GitlabProjDetail;
if (body.message === "404 Project Not Found") return null;
return body;
} catch {
return null;
}
};
/**
* 线
*/
const fetchPipelines = async (project_id: number, page = 1) => {
try {
const response = await fetch(
`https://git.n.xiaomi.com/api/v4/projects/${project_id}/pipelines?scope=finished&per_page=100&page=${page}`,
fetchGetParams
);
const body = (await response.json()) as GitlabPipeline[] & GitlabError;
if (body?.message === "404 Project Not Found") return [];
return body;
} catch {
return [] as GitlabPipeline[];
}
};
/**
* 线
*/
const fetchPipelineDetails = async (
project_id: number,
pipeline_id: number,
created_at: string
) => {
try {
const response = await fetch(
`https://git.n.xiaomi.com/api/v4/projects/${project_id}/pipelines/${pipeline_id}`,
fetchGetParams
);
const body = (await response.json()) as GitlabPipelineDetail;
if (body.message === "404 Project Not Found") return null;
return {
...body,
created_at,
};
} catch {
return null;
}
};
const sendMessage = async (body: string) => {
try {
const response = await fetch("https://egg.imoaix.cn/message", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body,
});
const res = await response.json();
return res;
} catch {
return null;
}
};
sendMessage.byGroupId = async (group_id: string, content: string) => {
const body = JSON.stringify({
group_id,
msg_type: "interactive",
content,
});
return sendMessage(body);
};
sendMessage.byChatId = async (chat_id: string, content: string) => {
const body = JSON.stringify({
receive_id: chat_id,
receive_id_type: "chat_id",
msg_type: "interactive",
content,
});
return sendMessage(body);
};
import egg from "./egg";
import gitlab from "./gitlab";
const service = {
fetchProjectDetails,
fetchPipelines,
fetchPipelineDetails,
sendMessage,
gitlab,
egg,
};
export default service;

98
service/netTool.ts Normal file
View File

@ -0,0 +1,98 @@
interface NetGetParams {
url: string;
method: string;
params?: any;
data?: any;
headers?: any;
}
/**
*
* @param response
* @param method
* @param data
*/
const logResponse = async (
response: Response,
method: string,
data: any,
headers: any
) => {
let responseData = null;
try {
responseData = await response.json();
} catch (error) {
responseData = "parse to json error";
}
const responseLog = {
ok: response.ok,
status: response.status,
statusText: response.statusText,
url: response.url,
method: method,
requestHeaders: headers,
responseHeaders: response.headers,
requestBody: data,
responseBody: responseData as any,
};
console.log("🚀 ~ responseLog:", JSON.stringify(responseLog, null, 2));
return responseLog;
};
const netTool = <T = any>({
url,
method,
params,
data,
headers,
}: NetGetParams): Promise<T> => {
let fullUrl = url;
if (params) {
if (typeof params === "string") {
fullUrl = `${url}?${params}`;
} else {
const queryString = new URLSearchParams(params).toString();
fullUrl = `${url}?${queryString}`;
}
}
return fetch(fullUrl, {
method,
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
...headers,
},
})
.then((response) => logResponse(response, method, data, headers))
.then((responseLog) => {
if (!responseLog.ok) {
if (responseLog?.responseBody?.msg) {
throw new Error(responseLog.responseBody.msg);
}
throw new Error("网络响应异常");
}
if (responseLog.responseBody === "parse to json error") {
throw new Error("解析响应数据异常");
}
return responseLog.responseBody as T;
});
};
netTool.get = <T = any>(url: string, params?: any, headers?: any): Promise<T> =>
netTool({ url, method: "get", params, headers });
netTool.post = <T = any>(
url: string,
data?: any,
params?: any,
headers?: any
): Promise<T> => netTool({ url, method: "post", data, params, headers });
netTool.del = <T = any>(url: string, data: any, headers?: any): Promise<T> =>
netTool({ url, method: "delete", data, headers });
netTool.patch = <T = any>(url: string, data: any, headers?: any): Promise<T> =>
netTool({ url, method: "patch", data, headers });
export default netTool;