baseComponent.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 qiniu from 'qiniu'
  7. qiniu.conf.ACCESS_KEY = 'Ep714TDrVhrhZzV2VJJxDYgGHBAX-KmU1xV1SQdS';
  8. qiniu.conf.SECRET_KEY = 'XNIW2dNffPBdaAhvm9dadBlJ-H6yyCTIJLxNM_N6';
  9. export default class BaseComponent {
  10. constructor(){
  11. this.idList = ['restaurant_id', 'food_id', 'order_id', 'user_id', 'address_id', 'cart_id', 'img_id', 'category_id', 'item_id', 'sku_id', 'admin_id', 'statis_id'];
  12. this.imgTypeList = ['shop', 'food', 'avatar','default'];
  13. this.uploadImg = this.uploadImg.bind(this)
  14. this.qiniu = this.qiniu.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. try{
  75. const image_path = await this.qiniu(req, type);
  76. res.send({
  77. status: 1,
  78. image_path,
  79. })
  80. }catch(err){
  81. console.log('上传图片失败', err);
  82. res.send({
  83. status: 0,
  84. type: 'ERROR_UPLOAD_IMG',
  85. message: '上传图片失败'
  86. })
  87. }
  88. }
  89. async qiniu(req, type = 'default'){
  90. return new Promise((resolve, reject) => {
  91. const form = formidable.IncomingForm();
  92. form.uploadDir = './public/img/' + type;
  93. form.parse(req, async (err, fields, files) => {
  94. let img_id;
  95. try{
  96. img_id = await this.getId('img_id');
  97. }catch(err){
  98. console.log('获取图片id失败');
  99. fs.unlink(files.file.path);
  100. reject('获取图片id失败')
  101. }
  102. const imgName = (new Date().getTime() + Math.ceil(Math.random()*10000)).toString(16) + img_id;
  103. const extname = path.extname(files.file.name);
  104. const repath = './public/img/' + type + '/' + imgName + extname;
  105. try{
  106. const key = imgName + extname;
  107. await fs.rename(files.file.path, repath);
  108. const token = this.uptoken('node-elm', key);
  109. const qiniuImg = await this.uploadFile(token.toString(), key, repath);
  110. fs.unlink(repath);
  111. resolve(qiniuImg)
  112. }catch(err){
  113. console.log('保存至七牛失败', err);
  114. fs.unlink(files.file.path)
  115. reject('保存至七牛失败')
  116. }
  117. });
  118. })
  119. }
  120. uptoken(bucket, key){
  121. var putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
  122. return putPolicy.token();
  123. }
  124. uploadFile(uptoken, key, localFile){
  125. return new Promise((resolve, reject) => {
  126. var extra = new qiniu.io.PutExtra();
  127. qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
  128. if(!err) {
  129. resolve(ret.key)
  130. } else {
  131. console.log('图片上传至七牛失败', err);
  132. reject(err)
  133. }
  134. });
  135. })
  136. }
  137. }