From 3f56e6bf9a407a5f38e0dcf7f0bd7b6f9fcf739b Mon Sep 17 00:00:00 2001 From: Alexey Ivanov Date: Sat, 7 Mar 2020 03:32:11 +0900 Subject: [PATCH] Add middleware for redirects --- gatsby-config.js | 2 ++ middlewares/redirects/index.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 middlewares/redirects/index.js diff --git a/gatsby-config.js b/gatsby-config.js index b880042a77..02f6304939 100644 --- a/gatsby-config.js +++ b/gatsby-config.js @@ -6,6 +6,7 @@ require('./config/prismjs/dvc') require('./config/prismjs/usage') const apiMiddleware = require('./middlewares/api') +const redirectsMiddleware = require('./middlewares/redirects') const title = 'Data Version Control ยท DVC' const description = @@ -93,6 +94,7 @@ module.exports = { title }, developMiddleware: app => { + app.use(redirectsMiddleware) app.use('/api', apiMiddleware) } } diff --git a/middlewares/redirects/index.js b/middlewares/redirects/index.js new file mode 100644 index 0000000000..4d05936a17 --- /dev/null +++ b/middlewares/redirects/index.js @@ -0,0 +1,32 @@ +/* eslint-env node */ + +const { getRedirect } = require('../../src/utils/redirects') +const { parse } = require('url') +const { stringify } = require('querystring') + +const dev = process.env.NODE_ENV !== 'production' + +module.exports = (req, res, next) => { + const parsedUrl = parse(req.url, true) + const { pathname, query } = parsedUrl + const host = req.headers.host + + let [redirectCode, redirectLocation] = getRedirect(host, pathname, { + req, + dev + }) + + if (redirectLocation) { + // HTTP redirects + + const queryStr = stringify(query) + if (queryStr) { + redirectLocation += '?' + queryStr + } + res.writeHead(redirectCode, { + Location: redirectLocation + }) + } + + next() +}