baseComponent.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import fetch from 'node-fetch';
  2. import Ids from '../models/ids'
  3. export default class BaseComponent {
  4. constructor(){
  5. }
  6. async fetch(url = '', data = {}, type = 'GET', resType = 'JSON'){
  7. type = type.toUpperCase();
  8. resType = resType.toUpperCase();
  9. if (type == 'GET') {
  10. let dataStr = ''; //数据拼接字符串
  11. Object.keys(data).forEach(key => {
  12. dataStr += key + '=' + data[key] + '&';
  13. })
  14. if (dataStr !== '') {
  15. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  16. url = url + '?' + dataStr;
  17. }
  18. }
  19. let requestConfig = {
  20. method: type,
  21. headers: {
  22. 'Accept': 'application/json',
  23. 'Content-Type': 'application/json'
  24. },
  25. }
  26. if (type == 'POST') {
  27. Object.defineProperty(requestConfig, 'body', {
  28. value: JSON.stringify(data)
  29. })
  30. }
  31. let responseJson;
  32. try {
  33. const response = await fetch(url, requestConfig);
  34. if (resType === 'TEXT') {
  35. responseJson = await response.text();
  36. }else{
  37. responseJson = await response.json();
  38. }
  39. } catch (error) {
  40. console.error(error)
  41. throw new Error(error)
  42. }
  43. return responseJson
  44. }
  45. //获取id列表
  46. async getId(type){
  47. try{
  48. const idData = await Ids.findOne();
  49. idData[type] ++ ;
  50. await idData.save();
  51. return idData[type]
  52. }catch(err){
  53. throw new Error(err)
  54. }
  55. }
  56. }