Created
August 9, 2024 07:31
-
-
Save followdarko/e44c10a444aa7a713730993f1e1c1ea9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { WebServiceClient } from "@maxmind/geoip2-node"; | |
import zipState from "zip-state"; | |
const { MAXMIND_APP_ID, MAXMIND_APP_KEY } = process.env; | |
const DEFAULT_REGION = "NY"; | |
export async function getUSAStateFromZipOrIp({ | |
ip, | |
zip, | |
}: { | |
ip: string; | |
zip?: string; | |
}) { | |
const normalizedIp = ip.split(" ")[0]; | |
let region = DEFAULT_REGION; | |
let postal: string | null = zip || null; | |
let country = "US"; | |
let city = "empty"; | |
if (!zip) { | |
const client = new WebServiceClient(MAXMIND_APP_ID!, MAXMIND_APP_KEY!); | |
try { | |
const response = await client.city(normalizedIp); | |
const state = response?.subdivisions?.[0].isoCode; | |
const countryFromResponse = response?.country?.isoCode; | |
if (countryFromResponse === "US" && state) { | |
country = "US"; | |
region = state || DEFAULT_REGION; | |
postal = response?.postal?.code || null; | |
city = response?.city?.names.en || "empty"; | |
} | |
} catch (rejectedValue) { | |
console.warn("getUSAStateFromZipOrIp MAXMIND error: ", rejectedValue); | |
} | |
} else { | |
region = zipState(zip) ? zipState(zip) as string : DEFAULT_REGION; | |
} | |
return { | |
region, | |
postal, | |
country, | |
city, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment