如何将上传功能外包为服务notde.js

时间:2016-11-12 11:59:06

标签: javascript node.js architecture sails.js

我正在尝试将我的上传代码写成一项服务,因为我的软件需要整个功能。我的项目使用sails.js - 这里是service的文档。

在控制器中我得到了这个代码,它上传了一个文件,成功后它调用了saveTheCampaign()函数,并将文件信息保存在数据库中。

req.file('logo').upload({
         maxBytes: 10000000,
         saveAs: function (uploadFile, cb) {
         cb(null, Date.now() + uploadFile.filename);
         },
         dirname: sails.config.appPath + '/assets/images/campaign/'
         }, function (err, uploadedFiles) {
         if (err) {
         return res.json(500, err);
         }
         else if (uploadedFiles.length === 0) {
         // proceed without files
         res.json({ error: "No image found for upload!"})
         }
         else {
         //  Success: handle uploaded file
         var fileName = uploadedFiles[0].fd.split('\\');
         params["logo"] = fileName[fileName.length - 1];

         sails.controllers.campaign.saveTheCampaign(params, req, res);
         }
 });

 saveTheCampaign: function (params, req, res) { //...}

现在我想将此代码段写为服务。我的服务叫做UploadService,有一个名为upload()的函数,services可以带两(2)个参数,选项和回调函数。所以我试着调用我服务的上传功能:

UploadService.upload(options, sails.controllers.campaign.saveTheCampaign(params, req, res));

问题是,回调函数的参数(params,req,res)在调用时是未知的,我在上传函数完成后得到它们。我怎么处理这个?

1 个答案:

答案 0 :(得分:1)

使用Q Promise Library实现此目标的一种方法。下面的代码段是一个相同的工作示例。您需要为sails.config.appPath设置值。

<强> Routes.js

'POST /upload' : 'CampaignController.upload'

<强> UploadService.js

let q = require("q"); // https://github.com/kriskowal/q
module.exports = {
  upload: function(options) {
    let deferred = q.defer();
    options['req'].file(options['fileFieldName']).upload({
      maxBytes: 10,
      saveAs: function(uploadedFile, cb) {
        cb(null, Date.now() + uploadedFile.filename);
      },
      dirname: sails.config.appPath + '/assets/images/'
    }, function(err, uploadedFiles) {
      if (err) {
        deferred.reject(err);
      } else if (uploadedFiles.length === 0) {
        // proceed without files
        deferred.reject("No image found for upload!");
      } else {
        //  Success: handle uploaded file
        let params = [];
        var fileName = uploadedFiles[0].fd.split('\\');
        params["logo"] = fileName[fileName.length - 1];
        deferred.resolve(params)
      }
    });
    return deferred.promise;
  }
}

<强> CampaignController.js

module.exports = {
  upload: function(req, res) {
    let options = [];
    options['fileFieldName'] = 'logo';
    options['req'] = req;
    UploadService.upload(options)
      .then((params) => {
        sails.controllers.campaign.saveTheCampaign(params);
        res.send("Campaign Saved Successfully");
      })
      .catch((err) => res.send(err))
  },

  saveTheCampaign: function(params) {
    console.log(`campaign ${params['logo']} saved`);
  }
}