Resume

Wednesday, January 15, 2014

grunt-connect adding an upload handler for testing

Just a snippet for adding an upload handler to a grunt-connect livereload instance for testing file uploads.
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ],
          middleware: function (connect, options) {
            var middlewares = [

              connect().use(connect.bodyParser({ uploadDir: '.tmp' })),

              // save a file to temp and send a JSON response with basic file stats
              connect().use('/upload', function(req, res, next) {

                // files properties
                console.log(req.files);
                
                // { key: value } of form properties
                console.log(req.body);
                res.setHeader('Content-Type', 'application/json');

                // response with basic file stats
                res.end(JSON.stringify({ 'size': req.files.file.size, 'path' : req.files.file.path, 'error' : null }));
              })
            ];

            // add the static paths in options.base
            options.base.forEach(function (base) {
              middlewares.push(connect.static(base));
            });

            return middlewares;
          }
        }
      }