UNPKG

find-user-country

Version:

Find your user country

52 lines (51 loc) 2.87 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); function checkIsValidCountry(countryCode_1) { return __awaiter(this, arguments, void 0, function* (countryCode, options = { inspect: false }) { // get all countries database from github const getAllCountriesRes = yield fetch("https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/refs/heads/master/json/countries.json"); // if get all countries response is right... if (getAllCountriesRes.status === 200) { // help me for this code analyze... if (options.inspect) console.log("get all countries response status code is ", getAllCountriesRes.status); // get all countries with json format. const countries = yield getAllCountriesRes.json(); // if all countries is right... if (countries) { // help me for this code analyze... if (options.inspect) console.log("all countries datas are find!", JSON.stringify(countries[0], null, 2), "\n..."); // then loop in countries for the getting countryCode let userCountryCode = countries.find((country) => countryCode === country.iso2.toLowerCase()); if (userCountryCode) { // help me for this code analyze... if (options.inspect) console.log(`matched! your country code is valid!`, userCountryCode); return countryCode; } throw new Error(`user country code(${countryCode}) is not matched any countries!`); } // if countries is not found! else { throw new Error("Countries is not found on countries database!"); } } // get all countries response is not valid! else { throw new Error(`Failed to fetching all countries database! ${getAllCountriesRes.status ? `here is status code = ${getAllCountriesRes.status}` : ""}`); } }); } exports.default = checkIsValidCountry;