All files / tcb-admin-node/src/storage index.js

62.71% Statements 37/59
55% Branches 22/40
66.67% Functions 8/12
62.71% Lines 37/59
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 21114x 14x 14x               2x           2x               2x     2x     2x                         1x             1x 1x               1x         1x               1x     1x                         5x             5x 5x 5x 2x                   2x       3x 3x                     5x           5x                 5x     5x                   1x 1x 1x                 1x   1x     1x                                                                           14x 14x 14x 14x  
const request = require("request");
const fs = require('fs');
const httpRequest = require("../utils/httpRequest");
 
/*
 * 上传文件
 * @param {string} cloudPath 上传后的文件路径
 * @param {fs.ReadStream} fileContent  上传文件的二进制流
 */
function uploadFile({ cloudPath, fileContent }, { onResponseReceived } = {}) {
  let params = {
    action: "storage.uploadFile",
    path: cloudPath,
    file: fileContent
  };
 
  return httpRequest({
    config: this.config,
    params,
    method: "post",
    headers: {
      // "content-type": "multipart/form-data"
    },
    callback: (response) => {
      onResponseReceived && typeof onResponseReceived === 'function' && onResponseReceived(response)
    }
  }).then((res) => {
    Iif (res.code) {
      return res;
    } else {
      return {
        fileID: res.data.fileID,
        requestId: res.requestId
      };
    }
  });
}
 
/**
 * 删除文件
 * @param {Array.<string>} fileList 文件id数组
 */
async function deleteFile({ fileList }) {
  Iif (!fileList || !Array.isArray(fileList)) {
    return {
      code: "INVALID_PARAM",
      message: "fileList必须是非空的数组"
    };
  }
 
  for (let file of fileList) {
    Iif (!file || typeof file != "string") {
      return {
        code: "INVALID_PARAM",
        message: "fileList的元素必须是非空的字符串"
      };
    }
  }
 
  let params = {
    action: "storage.batchDeleteFile",
    fileid_list: fileList
  };
 
  return httpRequest({
    config: this.config,
    params,
    method: "post",
    headers: {
      "content-type": "application/json"
    }
  }).then(res => {
    Iif (res.code) {
      return res;
    } else {
      return {
        fileList: res.data.delete_list,
        requestId: res.requestId
      };
    }
  });
}
 
/**
 * 获取文件下载链接
 * @param {Array.<Object>} fileList
 */
async function getTempFileURL({ fileList }) {
  Iif (!fileList || !Array.isArray(fileList)) {
    return {
      code: "INVALID_PARAM",
      message: "fileList必须是非空的数组"
    };
  }
 
  let file_list = [];
  for (let file of fileList) {
    if (typeof file === 'object') {
      Iif (
        !file.hasOwnProperty("fileID") ||
        !file.hasOwnProperty("maxAge")
      ) {
        return {
          code: "INVALID_PARAM",
          message: "fileList的元素必须是包含fileID和maxAge的对象"
        };
      }
 
      file_list.push({
        fileid: file.fileID,
        max_age: file.maxAge
      });
    } else Eif (typeof file === 'string') {
      file_list.push({
        fileid: file,
      });
    } else {
      return {
        code: "INVALID_PARAM",
        message: "fileList的元素必须是字符串"
      };
    }
  }
 
  let params = {
    action: "storage.batchGetDownloadUrl",
    file_list
  };
  // console.log(params);
 
  return httpRequest({
    config: this.config,
    params,
    method: "post",
    headers: {
      "content-type": "application/json"
    }
  }).then(res => {
    // console.log(res);
    Iif (res.code) {
      return res;
    } else {
      return {
        fileList: res.data.download_list,
        requestId: res.requestId
      };
    }
  });
}
 
async function downloadFile({ fileID, tempFilePath }) {
  let tmpUrl,
    self = this;
  try {
    const tmpUrlRes = await this.getTempFileURL({
      fileList: [
        {
          fileID,
          maxAge: 600
        }
      ]
    });
    // console.log(tmpUrlRes);
    const res = tmpUrlRes.fileList[0]
 
    Eif (
      res.code != 'SUCCESS'
    ) {
      return res;
    }
 
    tmpUrl = res.tempFileURL;
  } catch (e) {
    throw e
  }
 
  let req = request({
    url: tmpUrl,
    encoding: null,
    proxy: self.config.proxy
  });
 
  return new Promise((resolve, reject) => {
    let fileContent = Buffer.alloc(0)
    req.on('response', function (response) {
      if (response && +response.statusCode === 200) {
        if (tempFilePath) {
          response.pipe(fs.createWriteStream(tempFilePath));
        } else {
          response.on('data', (data) => {
            fileContent = Buffer.concat([fileContent, data])
          })
        }
        response.on('end', () => {
          resolve({
            fileContent: tempFilePath ? undefined : fileContent,
            message: '文件下载完成'
          })
        })
      } else {
        reject(response)
      }
    });
  });
}
 
exports.uploadFile = uploadFile;
exports.deleteFile = deleteFile;
exports.getTempFileURL = getTempFileURL;
exports.downloadFile = downloadFile;