http.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var Gun = require('../gun')
  2. , formidable = require('formidable')
  3. , url = require('url');
  4. module.exports = function(req, res, next){
  5. next = next || function(){}; // if not next, and we don't handle it, we should res.end
  6. if(!req || !res){ return next() }
  7. if(!req.url){ return next() }
  8. if(!req.method){ return next() }
  9. var msg = {};
  10. msg.url = url.parse(req.url, true);
  11. msg.method = (req.method||'').toLowerCase();
  12. msg.headers = req.headers;
  13. var u, body
  14. , form = new formidable.IncomingForm()
  15. , post = function(err, body){
  16. if(u !== body){ msg.body = body }
  17. next(msg, function(reply){
  18. if(!res){ return }
  19. if(!reply){ return res.end() }
  20. if(Gun.obj.has(reply, 'statusCode') || Gun.obj.has(reply, 'status')){
  21. res.statusCode = reply.statusCode || reply.status;
  22. }
  23. if(reply.headers){
  24. if(!(res.headersSent || res.headerSent || res._headerSent || res._headersSent)){
  25. Gun.obj.map(reply.headers, function(val, field){
  26. if(val !== 0 && !val){ return }
  27. res.setHeader(field, val);
  28. });
  29. }
  30. }
  31. if(Gun.obj.has(reply,'chunk') || Gun.obj.has(reply,'write')){
  32. res.write(Gun.text.ify(reply.chunk || reply.write) || '');
  33. }
  34. if(Gun.obj.has(reply,'body') || Gun.obj.has(reply,'end')){
  35. res.end(Gun.text.ify(reply.body || reply.end) || '');
  36. }
  37. });
  38. }
  39. form.on('field',function(k,v){
  40. (body = body || {})[k] = v;
  41. }).on('file',function(k,v){
  42. return; // files not supported in gun yet
  43. }).on('error',function(e){
  44. if(form.done){ return }
  45. post(e);
  46. }).on('end', function(){
  47. if(form.done){ return }
  48. post(null, body);
  49. });
  50. form.parse(req);
  51. }