baseComponent.js 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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', 'order_id', '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. res.send({
  90. status: 0,
  91. type: 'ERROR_GET_ID',
  92. message: '获取图片id失败',
  93. })
  94. return
  95. }
  96. const imgUrl = (new Date().getTime() + Math.ceil(Math.random()*10000)).toString(16) + img_id;
  97. const extname = path.extname(files.file.name);
  98. const repath = './public/img/' + type + '/' + imgUrl + extname;
  99. try{
  100. await fs.rename(files.file.path, repath);
  101. gm(repath)
  102. .resize(400, 400, '!')
  103. .write(repath, async (err) => {
  104. if(err){
  105. console.log('改写图片尺寸失败');
  106. fs.unlink(repath);
  107. res.send({
  108. status: 0,
  109. type: 'ERROR_GET_SIZE',
  110. message: '改写图片尺寸失败',
  111. })
  112. }else{
  113. const path = repath.replace(/^\.\/public/, '');
  114. res.send({
  115. status: 1,
  116. image_path: path
  117. })
  118. }
  119. })
  120. }catch(err){
  121. console.log('改写图片路径失败');
  122. fs.unlink(files.file.path)
  123. res.send({
  124. status: 0,
  125. type: 'ERROR_USE_GM',
  126. message: '切图失败',
  127. })
  128. }
  129. });
  130. }
  131. }