2
0
Эх сурвалжийг харах

FB (but replacing promise)

yusueketk 7 жил өмнө
parent
commit
30fdae0fcd

+ 8 - 46
src/server/routes/attachment.js

@@ -11,19 +11,7 @@ module.exports = function(crowi, app) {
     , fileUploader = require('../service/file-uploader')(crowi, app)
     , ApiResponse = require('../util/apiResponse')
     , actions = {}
-    , api = {}
-    , AttachmentFile = {}
-    , mongoose = require('mongoose');
-
-  // instantiate mongoose-gridfs
-  var gridfs = require('mongoose-gridfs')({
-    collection: 'attachmentFiles',
-    model: 'AttachmentFile',
-    mongooseConnection: mongoose.connection
-  });
-
-  // obtain a model
-  AttachmentFile = gridfs.model;
+    , api = {};
 
   actions.api = api;
 
@@ -68,41 +56,15 @@ module.exports = function(crowi, app) {
    * @apiName get
    * @apiGroup Attachment
    *
-   * @apiParam {String} id
+   * @apiParam {String} pageId, fileId
    */
   api.get = async function(req, res) {
-    const id = req.params.id;
-
-    // AttachmentFile.find({filename: filePath}, async function(err, file) {
-    // if (err) {
-    //   throw new Error(err);
-    // }
-    // const id = file[0].id;
-    // const contentType = file[0].contentType;
-    const contentType = 'image/jpeg';
-    const readStream = new Promise((resolve, reject) => {
-      let buf;
-      const stream = AttachmentFile.readById(id);
-      stream.on('error', function(error) {
-        reject(error);
-      });
-      stream.on('data', function(data) {
-        if (buf) {
-          buf = Buffer.concat([buf, data]);
-        }
-        else {
-          buf = data;
-        }
-      });
-      stream.on('close', function() {
-        debug('GridFS readstream closed');
-        resolve(buf);
-      });
-    });
-    const data = await readStream;
-    res.set('Content-Type', contentType);
-    return res.send(ApiResponse.success(data));
-    // });
+    const pageId = req.params.pageId;
+    const fileId = req.params.fileId;
+    const filePath = `attachment/${pageId}/${fileId}`;
+    const fileData = await fileUploader.getFileData(filePath);
+    res.set('Content-Type', fileData.contentType);
+    return res.send(ApiResponse.success(fileData.data));
   };
 
   /**

+ 1 - 1
src/server/routes/index.js

@@ -176,7 +176,7 @@ module.exports = function(crowi, app) {
   app.get( '/:id([0-9a-z]{24})'       , loginRequired(crowi, app, false) , page.api.redirector);
   app.get( '/_r/:id([0-9a-z]{24})'    , loginRequired(crowi, app, false) , page.api.redirector); // alias
   app.get( '/download/:id([0-9a-z]{24})' , loginRequired(crowi, app, false) , attachment.api.download);
-  app.get('/files/:id([0-9a-z]{24})'  , loginRequired(crowi, app, false), attachment.api.get);
+  app.get( '/attachment/:pageId/:fileId'  , loginRequired(crowi, app, false), attachment.api.get);
 
   app.get( '/_search'                 , loginRequired(crowi, app, false) , search.searchPage);
   app.get( '/_api/search'             , accessTokenParser , loginRequired(crowi, app, false) , search.api.search);

+ 52 - 14
src/server/service/file-uploader/gridfs.js

@@ -31,15 +31,17 @@ module.exports = function(crowi) {
   //   });
   // };
 
-  // create or save a file
-  lib.uploadFile = async function(filePath, contentType, fileStream, options) {
+  lib.uploadFile = function(filePath, contentType, fileStream, options) {
     debug('File uploading: ' + filePath);
-    AttachmentFile.write({filename: filePath, contentType: contentType}, fileStream,
-      function(error, createdFile) {
-        if (error) {
-          throw new Error('Failed to upload ' + createdFile + 'to gridFS', error);
-        }
-      });
+    return new Promise(function(resolve, reject) {
+      AttachmentFile.write({filename: filePath, contentType: contentType}, fileStream,
+        function(error, createdFile) {
+          if (error) {
+            reject(error);
+          }
+          resolve();
+        });
+    });
   };
 
   lib.findDeliveryFile = function(fileId, filePath) {
@@ -78,22 +80,58 @@ module.exports = function(crowi) {
   //   }
   //   catch (e) {
   //     // no such file or directory
-  //     debug('Stats error', e);
+  //     debug('Stats error', e); // [TODO] error log of bunyan logger
   //     return true;
   //   }
 
   //   return false;
   };
 
+  lib.getFileData = async function(filePath) {
+    const file = await lib.getFile(filePath);
+    const id = file.id;
+    const contentType = file.contentType;
+    const data = await lib.readFileData(id);
+    return {data, contentType};
+  };
 
-  lib.generateUrl = async function(filePath) {
-    await AttachmentFile.find({filename: filePath},
-      function(err, file) {
+  lib.getFile = function(filePath) {
+    return new Promise((resolve, reject) => {
+      AttachmentFile.find({
+        filename: filePath
+      }, async function(err, file) {
         if (err) {
-          throw new Error(err);
+          reject(err);
+        }
+        resolve(file[0]);
+      });
+    });
+  };
+
+  lib.readFileData = function(id) {
+    return new Promise((resolve, reject) => {
+      let buf;
+      const stream = AttachmentFile.readById(id);
+      stream.on('error', function(error) {
+        reject(error);
+      });
+      stream.on('data', function(data) {
+        if (buf) {
+          buf = Buffer.concat([buf, data]);
+        }
+        else {
+          buf = data;
         }
-        return `/files/${file[0].id}`;
       });
+      stream.on('close', function() {
+        debug('GridFS readstream closed');
+        resolve(buf);
+      });
+    });
+  };
+
+  lib.generateUrl = function(filePath) {
+    return `/${filePath}`;
   };
 
   return lib;