Teken Aja

import axios, { AxiosResponse } from 'axios'

let tekenUrl: string = 'https://apix.sandbox-111094.com/v2/data'
let tekenApiKey: string = process.env.TEKEN_API_KEY

export const tekenProvince = async (): Promise<Record<string, any>> => {
	try {
		const resProvince: AxiosResponse = await axios.get(`${tekenUrl}/province`, {
			headers: { apikey: tekenApiKey }
		})

		return Object.keys(resProvince.data.data).map((val, index) => {
			return { province_id: val, province_name: Object.values(resProvince.data.data)[index] }
		})
	} catch (err: any) {
		return Promise.reject(err)
	}
}

export const tekenDistrict = async (): Promise<Record<string, any>> => {
	try {
		const data: Record<string, any> = await tekenProvince()
		let listData: Record<string, any>[] = []

		const districtData: Record<string, any>[] = await data.map(async ({ province_id }) => {
			const resDistrict: AxiosResponse = await axios.get(`${tekenUrl}/district?province=${province_id}`, {
				headers: { apikey: tekenApiKey }
			})

			const newDistrictData: Record<string, any>[] = []

			Object.keys(resDistrict.data.data).forEach((district, index) => {
				newDistrictData.push({ district_id: district, district_name: Object.values(resDistrict.data.data)[index] })
			})
			return newDistrictData
		})

		for (let i in districtData) {
			listData.push({ province: data[i], district: await districtData.flat(Infinity)[i] })
		}

		return listData
	} catch (err: any) {
		return Promise.reject(err)
	}
}

export const tekenSubDistrict = async (): Promise<Record<string, any>> => {
	try {
		let dukcapil: Record<string, any>[] = []
		const district: Record<string, any> = await tekenDistrict()

		const data: Record<string, any>[] = await district.map(async ({ province, district }) => {
			let listData: Record<string, any>[] = []

			let subdistrictData: Record<string, any>[] = await district.map(async ({ district_id }) => {
				const resSubdistrict: AxiosResponse = await axios.get(
					`${tekenUrl}/subdistrict?province=${province.province_id}&district=${district_id}`,
					{ headers: { apikey: tekenApiKey } }
				)

				const newSubdistrictData: Record<string, any>[] = []
				Object.keys(resSubdistrict.data.data).forEach((subdistrict, index) => {
					newSubdistrictData.push({ subdistrict_id: subdistrict, subdistrict_name: Object.values(resSubdistrict.data.data)[index] })
				})
				return newSubdistrictData
			})

			for (let i in subdistrictData) {
				listData.push({ province: province, subdistrict: await subdistrictData[i] })
			}

			return listData
		})

		for (let i in data) {
			dukcapil.push(await data[i])
		}

		return dukcapil
	} catch (err: any) {
		return Promise.reject(err)
	}
}
Restu Wahyu Saputra