import { elasticsearchClient } from './client.js';
import { config } from '../config.js';
import { City, CreateCityRequest, UpdateCityRequest } from '../types/city.js';
import { CityDocument } from '../types/elasticsearch.js';
const INDEX = config.elasticsearch.index;
/**
* Repository for CRUD operations on Italian cities
*/
export class CitiesRepository {
/**
* Create a new city
*/
async createCity(request: CreateCityRequest): Promise<City> {
const document: CityDocument = {
nome: request.nome,
};
const response = await elasticsearchClient.index({
index: INDEX,
document,
refresh: 'wait_for',
});
return {
id: response._id,
nome: request.nome,
};
}
/**
* Get all cities
*/
async getAllCities(): Promise<City[]> {
const response = await elasticsearchClient.search({
index: INDEX,
body: {
query: {
match_all: {},
},
size: 10000,
},
});
return response.hits.hits.map((hit: any) => ({
id: hit._id,
nome: hit._source.nome,
}));
}
/**
* Get a city by ID
*/
async getCityById(id: string): Promise<City | null> {
try {
const response = await elasticsearchClient.get({
index: INDEX,
id,
});
return {
id: response._id,
nome: (response._source as CityDocument).nome,
};
} catch (error: any) {
if (error.meta?.statusCode === 404) {
return null;
}
throw error;
}
}
/**
* Search cities by name
*/
async searchCitiesByName(name: string): Promise<City[]> {
const response = await elasticsearchClient.search({
index: INDEX,
body: {
query: {
match: {
nome: {
query: name,
fuzziness: 'AUTO',
},
},
},
},
});
return response.hits.hits.map((hit: any) => ({
id: hit._id,
nome: hit._source.nome,
}));
}
/**
* Update a city
*/
async updateCity(id: string, request: UpdateCityRequest): Promise<City | null> {
try {
await elasticsearchClient.update({
index: INDEX,
id,
doc: {
nome: request.nome,
},
refresh: 'wait_for',
});
return {
id,
nome: request.nome,
};
} catch (error: any) {
if (error.meta?.statusCode === 404) {
return null;
}
throw error;
}
}
/**
* Delete a city
*/
async deleteCity(id: string): Promise<boolean> {
try {
await elasticsearchClient.delete({
index: INDEX,
id,
refresh: 'wait_for',
});
return true;
} catch (error: any) {
if (error.meta?.statusCode === 404) {
return false;
}
throw error;
}
}
}