utils.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 { sign } = require('../common');
  18. /**
  19. * 请求腾讯云CMS接口公共方法
  20. * @param {string} action - 接口请求action
  21. * @param {object} payload - 接口请求体
  22. * @return {object} API返回的有效数据
  23. */
  24. async function request(action, payload) {
  25. const [timestamp, authorization] = sign('cms', JSON.stringify(payload));
  26. const { res } = await uniCloud.httpclient.request('https://cms.tencentcloudapi.com', {
  27. method: 'POST',
  28. headers: {
  29. 'Content-Type': 'application/json',
  30. 'X-TC-Action': action,
  31. 'X-TC-Region': 'ap-guangzhou',
  32. 'X-TC-Version': '2019-03-21',
  33. 'X-TC-Timestamp': timestamp,
  34. Authorization: authorization
  35. },
  36. data: payload,
  37. dataType: 'json'
  38. });
  39. const { status, statusMessage, data } = res;
  40. if (status !== 200) {
  41. throw new Error(`${action}接口调用失败[${status} - ${statusMessage}]`);
  42. }
  43. if (data.Response.Error) {
  44. throw new Error(data.Response.Error.Message);
  45. }
  46. return data.Response;
  47. }
  48. module.exports = { request };