bizmatch-project/bizmatch-server/src/geo/geo.service.ts

41 lines
1.3 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { readFileSync } from 'fs';
import path, { join } from 'path';
import { City, Geo, State } from 'src/models/server.model.js';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@Injectable()
export class GeoService {
geo:Geo;
constructor() {
this.loadGeo();
}
private loadGeo(): void {
const filePath = join(__dirname,'..', 'assets', 'geo.json');
const rawData = readFileSync(filePath, 'utf8');
this.geo = JSON.parse(rawData);
}
findCitiesStartingWith( prefix: string, state?:string): { city: string; state: string; state_code: string }[] {
const result: { city: string; state: string; state_code: string }[] = [];
this.geo.states.forEach((state: State) => {
state.cities.forEach((city: City) => {
if (city.name.toLowerCase().startsWith(prefix.toLowerCase())) {
result.push({
city: city.name,
state: state.name,
state_code: state.state_code
});
}
});
});
return state ? result.filter(e=>e.state_code.toLowerCase()===state.toLowerCase()) :result;
}
}