medusa-plugin-ip-lookup-maxmind-geoip2
Version:
A Medusa plugin to lookup a user's country based on IP using MaxMind
83 lines (82 loc) • 3.21 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getIp = exports.GET = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var getIp = exports.getIp = function getIp(req) {
var ips = req.headers['cf-connecting-ip'] || req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress || '';
if (typeof ips === 'string') {
ips = ips.split(',');
}
return ips[0].trim();
};
var GET = exports.GET = /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(req, res) {
var _data$country, configModule, ipLookupService, regionService, ipLookupConfig, ip, data, region;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
configModule = req.scope.resolve("configModule");
ipLookupService = req.scope.resolve("ipLookupService");
regionService = req.scope.resolve("regionService");
ipLookupConfig = configModule.plugins.find(function (p) {
return typeof p !== 'string' && (p === null || p === void 0 ? void 0 : p.resolve) === 'medusa-plugin-ip-lookup-maxmind-geoip2';
});
if (ipLookupConfig) {
_context.next = 7;
break;
}
throw new Error('No ip lookup config found');
case 7:
if (ipLookupConfig.options.route_enabled) {
_context.next = 9;
break;
}
throw new Error('Route not enabled');
case 9:
ip = getIp(req);
_context.next = 12;
return ipLookupService.lookupIp(ip);
case 12:
data = _context.sent;
if ((_data$country = data.country) !== null && _data$country !== void 0 && _data$country.isoCode) {
_context.next = 15;
break;
}
throw new Error("Couldn't detect country code.");
case 15:
_context.next = 17;
return regionService.retrieveByCountryCode(data.country.isoCode);
case 17:
region = _context.sent;
res.json({
error: false,
message: 'success',
region: region,
country_code: data.country.isoCode.toLowerCase()
});
_context.next = 24;
break;
case 21:
_context.prev = 21;
_context.t0 = _context["catch"](0);
res.status(500).json({
error: true,
message: process.env.NODE_ENV === 'production' || !process.env.DEV ? 'Internal server error' : _context.t0.message,
region: null,
country_code: null
});
case 24:
case "end":
return _context.stop();
}
}, _callee, null, [[0, 21]]);
}));
return function GET(_x, _x2) {
return _ref.apply(this, arguments);
};
}();