Skip to content
This repository has been archived by the owner on Dec 9, 2024. It is now read-only.

Commit

Permalink
Merge pull request #13 from zarathustra323/pass-app-to-redirect
Browse files Browse the repository at this point in the history
Pass Express app object to redirect handler
  • Loading branch information
zarathustra323 authored Jan 29, 2021
2 parents f356d16 + 9802201 commit 6dc14ab
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
4 changes: 3 additions & 1 deletion packages/marko-web/express/error-handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const render = (res, { statusCode, err, template }) => {
};

const redirectOrError = ({
app,
req,
res,
err,
Expand All @@ -42,7 +43,7 @@ const redirectOrError = ({
template,
fatalErrorHandler,
}) => {
getRedirect(req, redirectHandler).then((redirect) => {
getRedirect(req, redirectHandler, app).then((redirect) => {
if (redirect) {
const { code, to } = redirect;
res.redirect(code, to);
Expand Down Expand Up @@ -74,6 +75,7 @@ module.exports = (app, { template, redirectHandler, onFatalError }) => {
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
const statusCode = err.status || err.statusCode || 500;
const opts = {
app,
req,
res,
err,
Expand Down
10 changes: 8 additions & 2 deletions packages/marko-web/express/get-redirect.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ const query = gql`
* @param {object} req The Express request object.
* @param {function} [handler] An optional redirect handler to execute if no redirect was found.
* Must return an object of `{ to, code }` or `null`
* @param {object} app The Express app object.
*/
module.exports = async (req, handler) => {
module.exports = async (req, handler, app) => {
const { apollo, path, query: params } = req;
const from = path.replace(/\/$/, '');
const variables = { input: { from, params } };
Expand All @@ -24,7 +25,12 @@ module.exports = async (req, handler) => {
if (to) return websiteRedirect;
// Attempt to find a redirect using the handler.
if (typeof handler !== 'function') return null;
const result = await handler({ from, params, req });
const result = await handler({
from,
params,
req,
app,
});
if (!result || !result.to) return null;
return { ...result, code: result.code || 301 };
};

0 comments on commit 6dc14ab

Please sign in to comment.