Skip to content

Instantly share code, notes, and snippets.

@rmoura-92
Created February 12, 2018 19:10
Show Gist options
  • Save rmoura-92/b68f884394ea3f7ed5cb35b5f00cd422 to your computer and use it in GitHub Desktop.
Save rmoura-92/b68f884394ea3f7ed5cb35b5f00cd422 to your computer and use it in GitHub Desktop.
//
// Currency Middleware
// -----------------------------------------------------------------------------
app.use((req, res, next) => {
const cookie = {
name: "currency",
options: {
path: "/",
maxAge: 3650 * 24 * 3600 * 1000, // 10 years in miliseconds
},
url: "/currency/{currency}",
};
const currenciesPromise = new Promise(async (resolve, reject) => {
try {
const currencies = await Currency.findAll();
resolve(currencies);
} catch (e) {
reject(e);
}
});
currenciesPromise.then(
(currencies) => {
currencies.map(currency => currency.currency);
const currencyUrl = `^${cookie.url}`;
const changeCurrencyURL = new RegExp(currencyUrl.replace("/", "\\/").replace("{currency}", "(.*)"));
const match = changeCurrencyURL.exec(req.url);
if (match !== null) {
if (currencies.indexOf(match[1]) !== -1) {
res.cookie(cookie.name, match[1], cookie.options);
return res.redirect("back");
}
res.status(404).send("The currency is not supported.");
} else {
const currency = req.cookies[cookie.name] || req.headers["accept-currency"];
if (typeof currency !== "undefined") {
res.cookie(cookie.name, currency, cookie.options);
} else {
res.clearCookie(cookie.name);
}
}
next();
},
err => next(err),
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment