-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: make fetcher compactible for browsers
- Loading branch information
1 parent
e47789d
commit 67ae82f
Showing
1 changed file
with
39 additions
and
9 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,46 @@ | ||
import fs from 'fs' | ||
import path from 'path' | ||
|
||
type Language = 'en' | 'np' | ||
type Directory = 'districts' | 'provinces' | 'categories' | 'municipalities' | ||
|
||
export function fetcher(dir: Directory, lang: Language = 'en') { | ||
import districtsEn from '../../data/districts/en.json' | ||
import districtsNp from '../../data/districts/np.json' | ||
import provincesEn from '../../data/provinces/en.json' | ||
import provincesNp from '../../data/provinces/np.json' | ||
import categoriesEn from '../../data/categories/en.json' | ||
import categoriesNp from '../../data/categories/np.json' | ||
import municipalitiesEn from '../../data/municipalities/en.json' | ||
import municipalitiesNp from '../../data/municipalities/np.json' | ||
import { IDistrict } from '../entities/district' | ||
import { IProvince } from '../entities/province' | ||
import { IMunicipality } from '../entities/municipality' | ||
import { ICategory } from '../entities/category' | ||
|
||
const DATA_MAP = { | ||
districts: { en: districtsEn, np: districtsNp }, | ||
provinces: { en: provincesEn, np: provincesNp }, | ||
categories: { en: categoriesEn, np: categoriesNp }, | ||
municipalities: { en: municipalitiesEn, np: municipalitiesNp }, | ||
} as const | ||
|
||
export type DirectoryDataMap = { | ||
districts: IDistrict[] | ||
provinces: IProvince[] | ||
municipalities: IMunicipality[] | ||
categories: ICategory[] | ||
} | ||
|
||
export function fetcher<T extends Directory>( | ||
dir: T, | ||
lang: Language = 'en' | ||
): DirectoryDataMap[T] { | ||
try { | ||
const file = lang === 'np' ? 'np.json' : 'en.json' | ||
const jsonPath = path.join(__dirname, `../../data/${dir}/${file}`) | ||
const content = fs.readFileSync(jsonPath, 'utf-8') | ||
return JSON.parse(content) | ||
const data = DATA_MAP[dir][lang] as DirectoryDataMap[T] | ||
if (!data) { | ||
throw new Error( | ||
`Data not found for directory: ${dir} and language: ${lang}` | ||
) | ||
} | ||
return data | ||
} catch (error) { | ||
throw new Error(`Failed to load data from source`) | ||
throw new Error(`Failed to load data from source}`) | ||
} | ||
} |