utils.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (C) 2020 Tencent Cloud.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. 'use strict';
  17. const axios = require('axios');
  18. const { region } = require('./config');
  19. const { sign } = require('../common');
  20. /**
  21. * 请求腾讯云机器翻译公共方法
  22. * @param {string} action - 接口请求action
  23. * @param {object} payload - 接口请求体
  24. * @returns {object} API返回的有效数据
  25. */
  26. async function request(action, payload) {
  27. if (!region) {
  28. throw new Error('请在云函数TMT模块中配置region');
  29. }
  30. const [timestamp, authorization] = sign('tmt', JSON.stringify(payload));
  31. const options = {
  32. url: 'https://tmt.tencentcloudapi.com',
  33. method: 'POST',
  34. headers: {
  35. 'Content-Type': 'application/json',
  36. 'X-TC-Action': action,
  37. 'X-TC-Version': '2018-03-21',
  38. 'X-TC-Timestamp': timestamp,
  39. 'X-TC-Region': region,
  40. Authorization: authorization
  41. },
  42. data: payload
  43. };
  44. const response = await axios(options);
  45. const { status, statusText, data } = response;
  46. if (status !== 200) {
  47. throw new Error(`${action}接口调用失败[${status} - ${statusText}]`);
  48. }
  49. if (data.Response.Error) {
  50. throw new Error(data.Response.Error.Message);
  51. }
  52. return data.Response;
  53. }
  54. module.exports = { request };