baseComponent.js 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. import qiniu from 'qiniu'
  8. qiniu.conf.ACCESS_KEY = 'Ep714TDrVhrhZzV2VJJxDYgGHBAX-KmU1xV1SQdS';
  9. qiniu.conf.SECRET_KEY = 'XNIW2dNffPBdaAhvm9dadBlJ-H6yyCTIJLxNM_N6';
  10. export default class BaseComponent {
  11. constructor(){
  12. this.idList = ['restaurant_id', 'food_id', 'order_id', 'user_id', 'address_id', 'cart_id', 'img_id', 'category_id', 'item_id', 'sku_id'];
  13. this.imgTypeList = ['shop', 'food', 'avatar','default'];
  14. this.uploadImg = this.uploadImg.bind(this)
  15. }
  16. async fetch(url = '', data = {}, type = 'GET', resType = 'JSON'){
  17. type = type.toUpperCase();
  18. resType = resType.toUpperCase();
  19. if (type == 'GET') {
  20. let dataStr = ''; //数据拼接字符串
  21. Object.keys(data).forEach(key => {
  22. dataStr += key + '=' + data[key] + '&';
  23. })
  24. if (dataStr !== '') {
  25. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  26. url = url + '?' + dataStr;
  27. }
  28. }
  29. let requestConfig = {
  30. method: type,
  31. headers: {
  32. 'Accept': 'application/json',
  33. 'Content-Type': 'application/json'
  34. },
  35. }
  36. if (type == 'POST') {
  37. Object.defineProperty(requestConfig, 'body', {
  38. value: JSON.stringify(data)
  39. })
  40. }
  41. let responseJson;
  42. try {
  43. const response = await fetch(url, requestConfig);
  44. if (resType === 'TEXT') {
  45. responseJson = await response.text();
  46. }else{
  47. responseJson = await response.json();
  48. }
  49. } catch (error) {
  50. console.log('获取http数据失败');
  51. throw new Error(error)
  52. }
  53. return responseJson
  54. }
  55. //获取id列表
  56. async getId(type){
  57. if (!this.idList.includes(type)) {
  58. console.log('id类型错误');
  59. throw new Error('id类型错误');
  60. return
  61. }
  62. try{
  63. const idData = await Ids.findOne();
  64. idData[type] ++ ;
  65. await idData.save();
  66. return idData[type]
  67. }catch(err){
  68. console.log('获取ID数据失败');
  69. throw new Error(err)
  70. }
  71. }
  72. async uploadImg(req, res, next){
  73. const type = req.params.type;
  74. if (!this.imgTypeList.includes(type)) {
  75. console.log('前台传入参数错误');
  76. res.send({
  77. status: 0,
  78. type: 'ERROR_PARAMS',
  79. message: '参数错误',
  80. })
  81. return
  82. }
  83. const form = formidable.IncomingForm();
  84. form.uploadDir = './public/img/' + type;
  85. form.parse(req, async (err, fields, files) => {
  86. let img_id;
  87. try{
  88. img_id = await this.getId('img_id');
  89. }catch(err){
  90. console.log('获取图片id失败');
  91. fs.unlink(files.file.path)
  92. res.send({
  93. status: 0,
  94. type: 'ERROR_GET_ID',
  95. message: '获取图片id失败',
  96. })
  97. return
  98. }
  99. const imgName = (new Date().getTime() + Math.ceil(Math.random()*10000)).toString(16) + img_id;
  100. const extname = path.extname(files.file.name);
  101. const repath = './public/img/' + type + '/' + imgName + extname;
  102. try{
  103. const key = imgName + extname;
  104. await fs.rename(files.file.path, repath);
  105. const token = this.uptoken('node-elm', key);
  106. const qiniuImg = await this.uploadFile(token.toString(), key, repath);
  107. fs.unlink(repath);
  108. res.send({
  109. status: 1,
  110. image_path: qiniuImg
  111. })
  112. // gm(repath)
  113. // .resize(400, 400, '!')
  114. // .write(repath, async (err) => {
  115. // if(err){
  116. // console.log('改写图片尺寸失败');
  117. // fs.unlink(repath);
  118. // res.send({
  119. // status: 0,
  120. // type: 'ERROR_GET_SIZE',
  121. // message: '改写图片尺寸失败',
  122. // })
  123. // }else{
  124. // const path = repath.replace(/^\.\/public/, '');
  125. // res.send({
  126. // status: 1,
  127. // image_path: path
  128. // })
  129. // }
  130. // })
  131. }catch(err){
  132. console.log('改写图片路径失败', err);
  133. fs.unlink(files.file.path)
  134. res.send({
  135. status: 0,
  136. type: 'ERROR_USE_GM',
  137. message: '切图失败',
  138. })
  139. }
  140. });
  141. }
  142. uptoken(bucket, key){
  143. var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
  144. return putPolicy.token();
  145. }
  146. uploadFile(uptoken, key, localFile){
  147. return new Promise((resolve, reject) => {
  148. var extra = new qiniu.io.PutExtra();
  149. qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
  150. if(!err) {
  151. resolve(ret.key)
  152. } else {
  153. console.log('图片上传至七牛失败', err);
  154. reject(err)
  155. }
  156. });
  157. })
  158. }
  159. }