baseComponent.js 4.9 KB

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