vsivsi / meteor-file-collection

Extends Meteor Collections to handle file data using MongoDB gridFS.
http://atmospherejs.com/vsivsi/file-collection
Other
159 stars 37 forks source link

Custom response data after POST request. #129

Open bjornba opened 8 years ago

bjornba commented 8 years ago

Hello.

I'm using this package to store images uploaded with the Froala editor. When Froala sends a post request it expects to get a link to the uploaded image in response.

I managed to get this to work for me by creating a custom handler for post requests to my collection but what i'm wondering is whether it is possible to just change the response sent from the default post handler in the package.

My handler looks like:

handler: function (req, res, next) {
  // At the end of the handler function we call next() which calls file-collection's post handler.
  // In the post handler the file is saved to the gridFS collection and then the response headers
  // are written and the response ended.
  // To prevent file-collection's post handler from ending the response, we store the relevant functions
  // and replace them with our own where we can end the response with custom response headers/data.
  const storeResWriteHead = res.writeHead;
  const storeResEnd = res.end;

  // When file-collection's post handler calls writeHead/end, the functions below are called.
  // The stored functions are called with 'res' set as the 'this' object.
  res.writeHead = function() {
    storeResWriteHead.call(res, 200, {'Content-Type': 'application/json'});
  };
  res.end = function(){
    storeResEnd.call(res, '{"link": "gridfs/images/' + req.gridFS._id + '",'
      + '"fileName": "' + req.gridFS.filename + '",'
      + '"fileId": "' + req.gridFS._id + '" }');
  }

  // Let file-collection's post handler save the file.
  next();
}
vsivsi commented 8 years ago

Hi, thanks for your question. I think that your solution is reasonable (the custom handler.) I would be hesitant to include the link in the default response to the POST request for a couple of reasons:

Does this make sense to you?