94 lines
2.8 KiB
JavaScript
94 lines
2.8 KiB
JavaScript
#!/usr/bin/env node
|
|
|
|
/**
|
|
* Gitea API Client
|
|
* 提供调用 Gitea API 的工具函数
|
|
*/
|
|
|
|
const BASE_URL = 'http://47.107.61.133:3000/api/v1';
|
|
|
|
function getToken() {
|
|
// 优先从环境变量读取,其次从命令行参数读取
|
|
const token = process.env['GITEA_TOKEN47'];
|
|
if (!token) {
|
|
// 检查是否有命令行传入的 token
|
|
const tokenArg = process.argv.find(arg => arg.startsWith('--token='));
|
|
if (tokenArg) {
|
|
return tokenArg.replace('--token=', '');
|
|
}
|
|
throw new Error('环境变量 GITEA_TOKEN47 未设置,请设置环境变量或使用 --token= 参数');
|
|
}
|
|
return token;
|
|
}
|
|
|
|
async function giteaRequest(method, endpoint, data = null, params = {}) {
|
|
const token = getToken();
|
|
let url = `${BASE_URL}${endpoint}`;
|
|
|
|
// 添加查询参数
|
|
if (Object.keys(params).length > 0) {
|
|
const queryString = new URLSearchParams(params).toString();
|
|
url += `?${queryString}`;
|
|
}
|
|
|
|
const options = {
|
|
method,
|
|
headers: {
|
|
'Authorization': `token ${token}`,
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json'
|
|
}
|
|
};
|
|
|
|
if (data && (method === 'POST' || method === 'PATCH' || method === 'PUT')) {
|
|
options.body = JSON.stringify(data);
|
|
}
|
|
|
|
const response = await fetch(url, options);
|
|
|
|
// 处理响应
|
|
const contentType = response.headers.get('content-type');
|
|
if (contentType && contentType.includes('application/json')) {
|
|
const result = await response.json();
|
|
if (!response.ok) {
|
|
throw new Error(`API Error: ${response.status} - ${JSON.stringify(result)}`);
|
|
}
|
|
return result;
|
|
} else {
|
|
if (!response.ok) {
|
|
throw new Error(`API Error: ${response.status} - ${response.statusText}`);
|
|
}
|
|
return response.status === 204 ? null : await response.text();
|
|
}
|
|
}
|
|
|
|
// 导出工具函数
|
|
const gitea = {
|
|
get: (endpoint, params = {}) => giteaRequest('GET', endpoint, null, params),
|
|
post: (endpoint, data = {}) => giteaRequest('POST', endpoint, data),
|
|
patch: (endpoint, data = {}) => giteaRequest('PATCH', endpoint, data),
|
|
put: (endpoint, data = {}) => giteaRequest('PUT', endpoint, data),
|
|
delete: (endpoint) => giteaRequest('DELETE', endpoint)
|
|
};
|
|
|
|
// CLI 模式
|
|
if (require.main === module) {
|
|
const args = process.argv.slice(2);
|
|
const command = args[0];
|
|
|
|
if (command === 'get') {
|
|
const endpoint = args[1];
|
|
gitea.get(endpoint).then(result => console.log(JSON.stringify(result, null, 2)));
|
|
} else if (command === 'post') {
|
|
const endpoint = args[1];
|
|
const data = JSON.parse(args[2] || '{}');
|
|
gitea.post(endpoint, data).then(result => console.log(JSON.stringify(result, null, 2)));
|
|
} else {
|
|
console.log('Usage:');
|
|
console.log(' node gitea.js get <endpoint>');
|
|
console.log(' node gitea.js post <endpoint> <json-data>');
|
|
}
|
|
}
|
|
|
|
module.exports = gitea;
|