Skip to content

Instantly share code, notes, and snippets.

@followdarko
Created August 9, 2024 07:31
Show Gist options
  • Save followdarko/e44c10a444aa7a713730993f1e1c1ea9 to your computer and use it in GitHub Desktop.
Save followdarko/e44c10a444aa7a713730993f1e1c1ea9 to your computer and use it in GitHub Desktop.
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