const fs = require('fs'); const sm3 = require('sm3'); const requests = require('request'); function getWdCfg() { const cfg = JSON.parse(fs.readFileSync('./conf.json')); return cfg.wdCfg; } /** * 生成签名 * @param {number} ts timestamp * @param {string} appId appId * @param {string} appSecret appSecret * @returns */ function sign(appId, appSecret, ts) { console.log(`sign(${appId}, ${appSecret}, ${ts})`); return sm3(`${appId}|${appSecret}|${ts}`).toUpperCase(); } /** * 请求封装 * @param {string} url 路径 * @param {object} data 参数对象 */ function req(url, data) { const wdCfg = getWdCfg(); if (!wdCfg) throw new Error('找不到配置'); const { host, port, appId, termId, version, appVersion, appPackageName, digestType, encType, appSecret } = wdCfg; if (!appId || !appSecret || !host || !port) throw new Error('配置有误'); const ts = new Date().getTime(); const body = { appId, app: { termId, version, appVersion, appPackageName, digestType, encType, }, data: { timestamp: ts, sign: sign(appId, appSecret, ts), }, } if (data) { body.data = { ...body.data, ...data, } } const bodyStr = JSON.stringify(body); const reqUrl = `http://${host}:${port}/${url}`; console.log(`Url: ${reqUrl}\nRequestBody: ${bodyStr}`); return new Promise((resolve, reject) => { requests({ url: reqUrl, body: bodyStr, headers: { 'Content-Type': 'application/json; charset=utf-8', }, method: 'POST', }, (err, httpResponse, responseBody) => { //console.log(httpResponse.statusCode) if (err) { console.log(`Error: ${err.toString()}`); reject(err); return; } console.log(`Response: ${responseBody}`); // TODO: 返回参数统一解析 resolve(responseBody); }) }); } // 获取 workKey 接口 async function getWorkKey() { const result = await req('hcbmp/management/rest/getWorkKey'); // TODO: get workKey and cache it! } getWorkKey() .then() .catch(e => { console.log(e); });