Skip to content

Commit

Permalink
fix: moves locator to middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
migtarx committed Dec 18, 2023
1 parent 5a6f116 commit c4bdd01
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
10 changes: 4 additions & 6 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ const morgan = require('morgan');
const helmet = require('helmet');
const app = express();
const { assignId, skipStatics, skipStatusServer } = require('./middlewares/morgan');
const { locator } = require('./middlewares/locator');
const BootService = require('./services/boot.service');
const execMode = BootService.getExecutionMode();
const PORT = process.env.PORT || 3000;

app.use(express.json())
app.use(cookieParser());
app.use(locator);
app.use(helmet({
contentSecurityPolicy: false
}));
Expand All @@ -23,18 +25,14 @@ morgan.token('accepted-cookies', function(req) {
return Boolean(req.cookies['cookie-accepted']);
});
morgan.token('location', async function(req) {
const ip = execMode == "pro" ? req.headers['x-real-ip'] : req.ip;
const response = await fetch(`https://api.iplocation.net/?ip=${ip}`);
const data = await response.json();
const countryName = data.country_name;
return countryName;
return req.location;
});
morgan.token('id', function getId(req) {
return req.id;
});
app.use(assignId);
app.use(
morgan('{ \n Request ID: :id \n Request IP: :user-ip \n Request location: :location \n Method: :method \n Route: :url \n Status code: :status \n Response time: :response-time \n Accepted Cookies: :accepted-cookies \n}', {
morgan('{ \n Request ID: :id \n Request IP: :user-ip \n Request location: :location \n Method: :method \n Route: :url \n Status code: :status \n Response time: :response-time \n Accepted Cookies: :accepted-cookies \n}', {
skip: function (req, res) {
return skipStatics(req, res) || skipStatusServer(req, res);
}
Expand Down
12 changes: 12 additions & 0 deletions src/middlewares/locator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
async function locator(req, res, next) {
const ip = global.exec_mode == "pro" ? req.headers['x-real-ip'] : req.ip;
const response = await fetch(`https://api.iplocation.net/?ip=${ip}`);
const data = await response.json();
const countryName = data.country_name;
req.location = countryName;
next();
}

module.exports = {
locator
}

0 comments on commit c4bdd01

Please sign in to comment.