index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. const fs = require('fs');
  2. const sm3 = require('sm3');
  3. const requests = require('request');
  4. function getWdCfg() {
  5. const cfg = JSON.parse(fs.readFileSync('./conf.json'));
  6. return cfg.wdCfg;
  7. }
  8. /**
  9. * 生成签名
  10. * @param {number} ts timestamp
  11. * @param {string} appId appId
  12. * @param {string} appSecret appSecret
  13. * @returns
  14. */
  15. function sign(appId, appSecret, ts) {
  16. console.log(`sign(${appId}, ${appSecret}, ${ts})`);
  17. return sm3(`${appId}|${appSecret}|${ts}`).toUpperCase();
  18. }
  19. /**
  20. * 请求封装
  21. * @param {string} url 路径
  22. * @param {object} data 参数对象
  23. */
  24. function req(url, data) {
  25. const wdCfg = getWdCfg();
  26. if (!wdCfg) throw new Error('找不到配置');
  27. const {
  28. host,
  29. port,
  30. appId,
  31. termId,
  32. version,
  33. appVersion,
  34. appPackageName,
  35. digestType,
  36. encType,
  37. appSecret
  38. } = wdCfg;
  39. if (!appId || !appSecret || !host || !port) throw new Error('配置有误');
  40. const ts = new Date().getTime();
  41. const body = {
  42. appId,
  43. app: {
  44. termId,
  45. version,
  46. appVersion,
  47. appPackageName,
  48. digestType,
  49. encType,
  50. },
  51. data: {
  52. timestamp: ts,
  53. sign: sign(appId, appSecret, ts),
  54. },
  55. }
  56. if (data) {
  57. body.data = {
  58. ...body.data,
  59. ...data,
  60. }
  61. }
  62. const bodyStr = JSON.stringify(body);
  63. const reqUrl = `http://${host}:${port}/${url}`;
  64. console.log(`Url: ${reqUrl}\nRequestBody: ${bodyStr}`);
  65. return new Promise((resolve, reject) => {
  66. requests({
  67. url: reqUrl,
  68. body: bodyStr,
  69. headers: {
  70. 'Content-Type': 'application/json; charset=utf-8',
  71. },
  72. method: 'POST',
  73. }, (err, httpResponse, responseBody) => {
  74. //console.log(httpResponse.statusCode)
  75. if (err) {
  76. console.log(`Error: ${err.toString()}`);
  77. reject(err);
  78. return;
  79. }
  80. console.log(`Response: ${responseBody}`);
  81. // TODO: 返回参数统一解析
  82. resolve(responseBody);
  83. })
  84. });
  85. }
  86. // 获取 workKey 接口
  87. async function getWorkKey() {
  88. const result = await req('hcbmp/management/rest/getWorkKey');
  89. // TODO: get workKey and cache it!
  90. }
  91. getWorkKey()
  92. .then()
  93. .catch(e => {
  94. console.log(e);
  95. });