Files
steel_prices_service/commonApi.js
2026-01-06 11:01:47 +08:00

172 lines
5.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const axios = require('axios');
const login = require('./loginApi.js');
/**
* 钢材价格数据采集服务
* 从德钢云平台获取价格数据
*/
class SteelPriceCollector {
constructor() {
this.baseURL = 'https://xdwlgyl.yciccloud.com';
this.pageId = 'PG-D615-D8E2-2FD84B8D';
this.menuId = 'MK-A8B8-109E-13D34116';
}
/**
* 构建请求配置(先获取 Token
* @param {Object} params - 查询参数
* @param {string} params.startDate - 开始日期 (YYYY-MM-DD)
* @param {string} params.endDate - 结束日期 (YYYY-MM-DD)
* @param {number} params.page - 页码默认1
* @param {number} params.pageSize - 每页大小默认1000
* @returns {Promise<Object>} Axios请求配置
*/
async _buildConfig(params = {}) {
const {
startDate = new Date().toISOString().split('T')[0],
endDate = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
page = 1,
pageSize = 10
} = params;
// 先获取 Token
console.log('🔐 正在获取 Token...');
const tokenResult = await login.getToken();
if (!tokenResult.success) {
throw new Error(`Token 获取失败: ${tokenResult.error}`);
}
const tokenId = tokenResult.data;
console.log('✅ Token 获取成功:', tokenId);
// 构建查询条件对象
const searchParams = {
_PIRCE_DATE_DATE_START_: startDate,
_PIRCE_DATE_DATE_END_: endDate,
PARTSNAME_NAME: null,
_PARTSNAME_NAME_ADVANCE_SEARCH_: null,
_PARTSNAME_NAME_IS_LIKE_: '1',
GOODS_MATERIAL: null,
_GOODS_MATERIAL_ADVANCE_SEARCH_: null,
_GOODS_MATERIAL_IS_LIKE_: '1',
GOODS_SPEC: null,
_GOODS_SPEC_ADVANCE_SEARCH_: null,
_GOODS_SPEC_IS_LIKE_: '1',
PRODUCTAREA_NAME: null,
_PRODUCTAREA_NAME_ADVANCE_SEARCH_: null,
_PRODUCTAREA_NAME_IS_LIKE_: '1',
PNTREE_NAME: null,
_PNTREE_NAME_ADVANCE_SEARCH_: null,
_PNTREE_NAME_IS_LIKE_: '1',
OPERATOR_NAME: null,
_OPERATOR_NAME_ADVANCE_SEARCH_: null,
PR_PRICE_REGION: null,
_PR_PRICE_REGION_ADVANCE_SEARCH_: null,
OPERATOR_CODE: null,
PRICE_ID: null,
_orderFields_: []
};
// 构建URL编码的请求体
const requestData = new URLSearchParams({
pageId: this.pageId,
pageSize: pageSize.toString(),
page: page.toString(),
isPageNoChange: '0',
ctrlId: 'mainTable',
json: JSON.stringify(searchParams),
searchBoxId: 'searchForm',
groupSumFields: JSON.stringify([])
});
// 使用获取到的 Token 构建 Cookie
const cookie = `SameSite=Lax; HWWAFSESTIME=1767596069712; HWWAFSESID=e2b2773ee2641b98e5; SameSite=Lax; SYS-A7EE-D0E8-BE614B80=1108@${tokenId}; JSESSIONID=2389858DBE6A7EDAF695C767A764995B; SameSite=Lax`;
return {
method: 'POST',
url: `${this.baseURL}/gdpaas/mainpage/findPage.htm?_p_=${this.pageId}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'X-Requested-With': 'XMLHttpRequest',
'Pageid': 'PG_D615_D8E2_2FD84B8D',
'Menuid': this.menuId,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Referer': `${this.baseURL}/gdpaas/home/index.htm`,
'Origin': this.baseURL,
'Accept-Language': 'zh-CN,zh;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Dest': 'empty',
'Sec-Ch-Ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': '"Windows"',
'cookie': cookie
},
data: requestData.toString()
};
}
/**
* 获取钢材价格数据
* @param {Object} params - 查询参数
* @returns {Promise<Object>} 响应数据
*/
async fetchPrices(params = {}) {
try {
const config = await this._buildConfig(params);
const response = await axios.request(config);
// 验证响应数据
if (!response.data) {
throw new Error('响应数据为空');
}
return {
success: true,
data: response.data,
timestamp: new Date().toISOString()
};
} catch (error) {
return {
success: false,
error: error.message,
timestamp: new Date().toISOString()
};
}
}
}
/**
* 导出单例实例
*/
module.exports = new SteelPriceCollector();
/**
* 如果直接运行此文件,执行示例请求
*/
if (require.main === module) {
const collector = require('./commonApi.js');
// 示例:获取最近一年的价格数据
collector.fetchPrices({
startDate: '2025-01-06',
endDate: '2026-01-06',
page: 1,
pageSize: 1
})
.then(result => {
if (result.success) {
console.log('✅ 数据获取成功');
console.log('📅 时间:', result.timestamp);
console.log('📊 数据预览:', JSON.stringify(result.data, null, 2));
} else {
console.error('❌ 数据获取失败:', result.error);
}
})
.catch(error => {
console.error('💥 未捕获的错误:', error);
});
}