// src/services/db/address.db.ts import { getPool } from './connection.db'; import { logger } from '../logger.server'; import { Address } from '../../types'; /** * Retrieves a single address by its ID. * @param addressId The ID of the address to retrieve. * @returns A promise that resolves to the Address object or undefined. */ export async function getAddressById(addressId: number): Promise
{ try { const res = await getPool().query
('SELECT * FROM public.addresses WHERE address_id = $1', [addressId]); return res.rows[0]; } catch (error) { logger.error('Database error in getAddressById:', { error, addressId }); throw new Error('Failed to retrieve address.'); } } /** * Creates or updates an address and returns its ID. * This function uses an "upsert" pattern. * @param address The address data. * @returns The ID of the created or updated address. */ export async function upsertAddress(address: Partial
): Promise { const { address_id, address_line_1, address_line_2, city, province_state, postal_code, country, latitude, longitude } = address; const locationPoint = latitude && longitude ? `ST_SetSRID(ST_MakePoint(${longitude}, ${latitude}), 4326)` : null; // If an ID is provided, it's an update. Otherwise, it's an insert. if (address_id) { const query = ` UPDATE public.addresses SET address_line_1 = $1, address_line_2 = $2, city = $3, province_state = $4, postal_code = $5, country = $6, latitude = $7, longitude = $8, location = ${locationPoint}, updated_at = now() WHERE address_id = $9 RETURNING address_id; `; const res = await getPool().query(query, [address_line_1, address_line_2, city, province_state, postal_code, country, latitude, longitude, address_id]); return res.rows[0].address_id; } else { const query = ` INSERT INTO public.addresses (address_line_1, address_line_2, city, province_state, postal_code, country, latitude, longitude, location) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, ${locationPoint}) RETURNING address_id; `; const res = await getPool().query(query, [address_line_1, address_line_2, city, province_state, postal_code, country, latitude, longitude]); return res.rows[0].address_id; } }