Skip to content

Instantly share code, notes, and snippets.

@brunnels
Created October 25, 2016 16:48
Show Gist options
  • Save brunnels/3011f52c3dddcc6822d805b01952a7b6 to your computer and use it in GitHub Desktop.
Save brunnels/3011f52c3dddcc6822d805b01952a7b6 to your computer and use it in GitHub Desktop.
'use strict';
var gulp = require('gulp'),
util = require('./utils'),
url = require('url'),
browserSync = require('browser-sync'),
proxy = require('proxy-middleware');
var config = require('./config');
module.exports = function () {
//var baseUri = config.uri + config.apiPort;
// Routes to proxy to the backend. Routes ending with a / will setup
// a redirect so that if accessed without a trailing slash, will
// redirect. This is required for some endpoints for proxy-middleware
// to correctly handle them.
var proxyRoutes = [
{ route: '/', baseUri: config.uri + config.apiPort}
];
var requireTrailingSlash = proxyRoutes.filter(function (r) {
return util.endsWith(r.baseUri, '/');
}).map(function (r) {
// Strip trailing slash so we can use the route to match requests
// with non trailing slash
r.baseUri = r.baseUri.substr(0, r.baseUri.length - 1);
return r
});
var proxies = [
// Ensure trailing slash in routes that require it
function (req, res, next) {
requireTrailingSlash.forEach(function (r){
if (url.parse(req.url).path === r.route) {
res.statusCode = 301;
res.setHeader('Location', r.route + '/');
res.end();
}
});
next();
}
]
.concat(
// Build a list of proxies for routes: [route1_proxy, route2_proxy, ...]
proxyRoutes.map(function (r) {
var options = url.parse(r.baseUri + r.route);
options.route = r.route;
options.preserveHost = true;
return proxy(options);
}));
browserSync({
open: false,
port: config.port,
server: {
baseDir: config.app,
middleware: proxies
}
});
gulp.start('watch');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment