Skip to content

Instantly share code, notes, and snippets.

@lwakefield
Created May 25, 2016 23:24
Show Gist options
  • Save lwakefield/fa67ee09f7a411573e1dc471f7d541f7 to your computer and use it in GitHub Desktop.
Save lwakefield/fa67ee09f7a411573e1dc471f7d541f7 to your computer and use it in GitHub Desktop.
import { Meteor } from 'meteor/meteor';
WebApp.connectHandlers.use('/file', (req, res) => {
// We only care about PUT methods
res.setHeader("Access-Control-Allow-Methods", "PUT");
// I am running meteor as a backend, see https://iamlawrence.me/agnostic-meteor
// Therefore we need to enable CORS
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
// When sending a CORS request, a 'preflight' request is sent.
// This will determine what methods are allowed on this endpoint.
// Just respond happily with a 200 response
// See more here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
} else if (req.method === 'PUT') {
// In this example, I only care about images...
if (!req.headers['content-type'].startsWith('image')) {
res.writeHead(400);
res.end();
}
// Because the 'readable' and 'end' events are async
// we wrap them with wrapAsync, because we want to
// receive the entire file before sending our response.
// Read up on this here http://docs.meteor.com/api/core.html#Meteor-wrapAsync
let getFile = Meteor.wrapAsync(done => {
let chunks = [];
req.on('readable', () => {
chunks.push(req.read());
});
req.on('end', () => {
done(undefined, Buffer.concat(chunks));
});
});
// We grab the file using the wrapped async method
// that we just created above.
let buffer = getFile();
// Now you can do whatever you want with this file.
// Pass it onto S3, write it to the File System,
// exec the file directly...
// Actually, please don't do that. Please.
// We can finally reply happily!
res.writeHead(200);
res.end();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment