Skip to content

Commit

Permalink
Add middleware for redirects
Browse files Browse the repository at this point in the history
  • Loading branch information
iAdramelk committed Mar 6, 2020
1 parent e0509ab commit c92f450
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
4 changes: 3 additions & 1 deletion gatsby-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -93,6 +94,7 @@ module.exports = {
title
},
developMiddleware: app => {
app.use('/api', apiMiddleware)
app.use(redirectsMiddleware)
app.get('/api', apiMiddleware)
}
}
32 changes: 32 additions & 0 deletions middlewares/redirects/index.js
Original file line number Diff line number Diff line change
@@ -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()
}

0 comments on commit c92f450

Please sign in to comment.