Skip to content

Commit

Permalink
add redirect feature
Browse files Browse the repository at this point in the history
  • Loading branch information
VovaStelmashchuk committed Sep 16, 2024
1 parent 343de66 commit 91522dc
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
1 change: 0 additions & 1 deletion database/tool.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

const Database = require('./newclient');

function getToolBySlug(slug) {
Expand Down
22 changes: 22 additions & 0 deletions features/redirects/check.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const Database = require('../../database/newclient');

async function checkIsUrlNeedRedirect(url) {
url = url.replace(/^\/|\/$/g, '');

const redirect = await Database.collection('redirects').findOne({ from: url });

if (redirect) {
return {
isRedirect: true,
to: redirect.to,
};
} else {
return {
isRedirect: false,
};
}
}

module.exports = {
checkIsUrlNeedRedirect,
};
17 changes: 17 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const toolDetails = require('./features/tools/rest');
const goodDetails = require('./features/goods/rest');
const filter = require('./features/filters/rest');
const siteMap = require('./features/sitemap/rest');
const { checkIsUrlNeedRedirect } = require('./features/redirects/check');

const app = express();
const port = process.env.APP_PORT;
Expand All @@ -26,6 +27,22 @@ app.use(cors({

app.use(express.json());

async function redirectIfXUserPath(req, res, next) {
const xUserPath = req.headers['x-user-path'];

if (xUserPath) {
const redirect = await checkIsUrlNeedRedirect(xUserPath)

if (redirect.isRedirect == true) {
return res.status(200).json({ redirect: redirect.to });
}
}
next();
}

// Use the middleware in your Express app
app.use(redirectIfXUserPath);

app.use(
postListRoutes,
postDetailsRoutes,
Expand Down

0 comments on commit 91522dc

Please sign in to comment.