61 lines
2.5 KiB
JavaScript
61 lines
2.5 KiB
JavaScript
const fs = require('fs')
|
|
const path = require('path')
|
|
const { CountryModel, ProvinceModel, CityModel } = require('../models/StateCity')
|
|
|
|
/**
|
|
* Single source of truth for keeping the Country/Province/City reference
|
|
* collections in sync with data/geo/{countries,provinces,cities}.json.
|
|
* Runs automatically on every backend boot (see boot/mongo.js) — no manual
|
|
* script to remember to re-run when the JSON files change. Cheap no-op when
|
|
* already in sync (only a countDocuments() + JSON parse), unless force=true.
|
|
*/
|
|
async function ensureGeoData(force = false) {
|
|
const dataDir = path.join(__dirname, '../data/geo')
|
|
const countries = JSON.parse(fs.readFileSync(path.join(dataDir, 'countries.json'), 'utf8'))
|
|
const provinces = JSON.parse(fs.readFileSync(path.join(dataDir, 'provinces.json'), 'utf8'))
|
|
const cities = JSON.parse(fs.readFileSync(path.join(dataDir, 'cities.json'), 'utf8'))
|
|
|
|
const provincesWithFaCount = provinces.filter((p) => p.name_fa).length
|
|
const citiesWithFaCount = cities.filter((c) => c.name_fa).length
|
|
|
|
const [countryCount, provinceCount, cityCount, provinceFaCount, cityFaCount] = await Promise.all([
|
|
CountryModel.countDocuments(),
|
|
ProvinceModel.countDocuments(),
|
|
CityModel.countDocuments(),
|
|
ProvinceModel.countDocuments({ name_fa: { $exists: true, $ne: null } }),
|
|
CityModel.countDocuments({ name_fa: { $exists: true, $ne: null } })
|
|
])
|
|
const inSync =
|
|
countryCount === countries.length &&
|
|
provinceCount === provinces.length &&
|
|
cityCount === cities.length &&
|
|
provinceFaCount === provincesWithFaCount &&
|
|
cityFaCount === citiesWithFaCount
|
|
if (!force && inSync) return
|
|
|
|
console.log(`[boot] Geo reference data out of sync (countries: ${countryCount}/${countries.length}, provinces: ${provinceCount}/${provinces.length}, cities: ${cityCount}/${cities.length}, city name_fa: ${cityFaCount}/${citiesWithFaCount}) — reseeding...`)
|
|
|
|
await CountryModel.deleteMany({})
|
|
await ProvinceModel.deleteMany({})
|
|
await CityModel.deleteMany({})
|
|
|
|
await CountryModel.insertMany(countries)
|
|
await ProvinceModel.insertMany(
|
|
provinces.map((p) => ({ id: p.id, name: p.name, name_fa: p.name_fa, slug: p.slug, country_id: p.country_id }))
|
|
)
|
|
await CityModel.insertMany(
|
|
cities.map((c) => ({
|
|
id: c.id,
|
|
name: c.name,
|
|
name_fa: c.name_fa,
|
|
slug: c.slug,
|
|
province_id: c.province_id,
|
|
country_id: c.country_id
|
|
}))
|
|
)
|
|
|
|
console.log(`[boot] Geo reference data reseeded: ${countries.length} countries, ${provinces.length} provinces, ${cities.length} cities.`)
|
|
}
|
|
|
|
module.exports = { ensureGeoData }
|