baseComponent.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import fetch from 'node-fetch';
  2. import Ids from '../models/ids'
  3. import formidable from 'formidable'
  4. import path from 'path'
  5. import fs from 'fs'
  6. import gm from 'gm'
  7. export default class BaseComponent {
  8. constructor(){
  9. this.idList = ['restaurant_id', 'food_id', 'orderId', 'user_id', 'address_id', 'cart_id', 'img_id', 'category_id', 'item_id', 'sku_id'];
  10. this.imgTypeList = ['shop', 'food', 'avatar','default'];
  11. this.uploadImg = this.uploadImg.bind(this)
  12. }
  13. async fetch(url = '', data = {}, type = 'GET', resType = 'JSON'){
  14. type = type.toUpperCase();
  15. resType = resType.toUpperCase();
  16. if (type == 'GET') {
  17. let dataStr = ''; //数据拼接字符串
  18. Object.keys(data).forEach(key => {
  19. dataStr += key + '=' + data[key] + '&';
  20. })
  21. if (dataStr !== '') {
  22. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  23. url = url + '?' + dataStr;
  24. }
  25. }
  26. let requestConfig = {
  27. method: type,
  28. headers: {
  29. 'Accept': 'application/json',
  30. 'Content-Type': 'application/json'
  31. },
  32. }
  33. if (type == 'POST') {
  34. Object.defineProperty(requestConfig, 'body', {
  35. value: JSON.stringify(data)
  36. })
  37. }
  38. let responseJson;
  39. try {
  40. const response = await fetch(url, requestConfig);
  41. if (resType === 'TEXT') {
  42. responseJson = await response.text();
  43. }else{
  44. responseJson = await response.json();
  45. }
  46. } catch (error) {
  47. console.log('获取http数据失败');
  48. throw new Error(error)
  49. }
  50. return responseJson
  51. }
  52. //获取id列表
  53. async getId(type){
  54. if (!this.idList.includes(type)) {
  55. console.log('id类型错误');
  56. throw new Error('id类型错误');
  57. return
  58. }
  59. try{
  60. const idData = await Ids.findOne();
  61. idData[type] ++ ;
  62. await idData.save();
  63. return idData[type]
  64. }catch(err){
  65. console.log('获取ID数据失败');
  66. throw new Error(err)
  67. }
  68. }
  69. async uploadImg(req, res, next){
  70. const type = req.params.type;
  71. if (!this.imgTypeList.includes(type)) {
  72. console.log('前台传入参数错误');
  73. res.send({
  74. status: 0,
  75. type: 'ERROR_PARAMS',
  76. message: '参数错误',
  77. })
  78. return
  79. }
  80. const form = formidable.IncomingForm();
  81. form.uploadDir = './public/img/' + type;
  82. form.parse(req, async (err, fields, files) => {
  83. let img_id;
  84. try{
  85. img_id = await this.getId('img_id');
  86. }catch(err){
  87. console.log('获取图片id失败');
  88. fs.unlink(files.file.path)
  89. reject(err);
  90. }
  91. const imgUrl = (new Date().getTime() + Math.ceil(Math.random()*10000)).toString(16) + img_id;
  92. const extname = path.extname(files.file.name);
  93. const repath = './public/img/' + type + '/' + imgUrl + extname;
  94. try{
  95. await fs.rename(files.file.path, repath);
  96. gm(repath)
  97. .resize(400, 400, '!')
  98. .write(repath, async (err) => {
  99. if(err){
  100. console.log('改写图片尺寸失败');
  101. fs.unlink(repath);
  102. reject(err);
  103. }else{
  104. const path = repath.replace(/^\.\/public/, '');
  105. res.send({
  106. status: 1,
  107. image_path: path
  108. })
  109. }
  110. })
  111. }catch(err){
  112. console.log('改写图片路径失败');
  113. fs.unlink(files.file.path)
  114. reject(err);
  115. }
  116. });
  117. }
  118. }