Skip to content

Instantly share code, notes, and snippets.

@billinghamj
Created April 14, 2016 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billinghamj/85d84750bd1624b0b2ad8d6ecab5dadc to your computer and use it in GitHub Desktop.
Save billinghamj/85d84750bd1624b0b2ad8d6ecab5dadc to your computer and use it in GitHub Desktop.
import express from 'express';
import request from 'request';
const app = express();
export default app;
const preRequestRouter = new express.Router();
const postRequestRouter = new express.Router();
// middleware is run in order
// when next() is called, the next one is run
// if one doesn't call next(), the process stops
app.use(preRequestRouter);
app.use(scRequest);
app.use(postRequestRouter);
app.use(scOutput);
function scRequest(req, res, next) {
req.headers.host = void 0;
const options = {
method: req.method,
url: `https://example.com${req.originalUrl}`,
headers: req.headers,
body: req.body,
...req.scRequestOverride,
};
request(options, function (err, result) {
if (err) {
next(err);
return;
}
req.scResult = result;
next();
});
}
function scOutput(req, res) {
res.status(req.scResult.status);
res.send(req.scResult.body);
}
// stops the request immediately, doesn't forward to snapchat
preRequestRouter.get('/blahblah', function (req, res) {
res.status(500);
res.json({ yeaahhh: '...no' });
});
// changes the method to post, then forwards to snapchat
preRequestRouter.get('/asdf', function (req, res, next) {
req.scRequestOverride = {
method: 'POST',
};
next();
});
// logs the snapchat output, outputs something else, and stops the request
postRequestRouter.get('/foo', function (req, res) {
console.log(req.scResult);
res.sendStatus(204);
});
// overrides part of the snapchat response, then continues
postRequestRouter.get('/bar', function (req, res, next) {
res.scResult.message = 'insert very offensive joke here';
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment