Adds ip lookup middleware for cart creation
This commit is contained in:
1 parent
79cc7e6639
commit
eeca05117a
11 files changed
+154
-23
No files matched your search
@@ -0,0 +1,36 @@
|
||||
export default {
|
||||
preCartCreation: async function (req, res, next) {
|
||||
try {
|
||||
if (req.body.region_id) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
const ipLookupService = req.scope.resolve("ipLookupService")
|
||||
const regionService = req.scope.resolve("regionService")
|
||||
|
||||
const ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress
|
||||
|
||||
const { data } = await ipLookupService.lookupIp(ip)
|
||||
|
||||
if (!data.country_code) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// Find region using the country code from ip lookup
|
||||
const regions = await regionService.list({
|
||||
countries: data.country_code,
|
||||
})
|
||||
|
||||
// If this region exists, add it to the body of the cart creation request
|
||||
if (regions[0]) {
|
||||
req.body.region_id = regions[0]._id.toString()
|
||||
}
|
||||
|
||||
next()
|
||||
} catch (error) {
|
||||
next()
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { BaseService } from "medusa-interfaces"
|
||||
import axios from "axios"
|
||||
|
||||
class IpLookupService extends BaseService {
|
||||
constructor({}, options) {
|
||||
super()
|
||||
|
||||
this.options_ = options
|
||||
}
|
||||
|
||||
async lookupIp(ipAddress) {
|
||||
return axios.get(
|
||||
`http://api.ipstack.com/${ipAddress}?access_key=${this.options_.access_token}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default IpLookupService
|
||||
Reference in new issue
Block a user