All checks were successful
Deploy to Test Environment / deploy-to-test (push) Successful in 17m30s
37 lines
1.4 KiB
TypeScript
37 lines
1.4 KiB
TypeScript
// src/services/userService.ts
|
|
import * as db from './db/index.db';
|
|
import { AddressRepository } from './db/address.db';
|
|
import { UserRepository } from './db/user.db';
|
|
import type { Address, UserProfile } from '../types';
|
|
|
|
/**
|
|
* Encapsulates user-related business logic that may involve multiple repository calls.
|
|
*/
|
|
class UserService {
|
|
/**
|
|
* Per ADR-002, this function encapsulates a multi-write operation within a transaction.
|
|
* It creates or updates a user's address and links it to their profile atomically.
|
|
*
|
|
* @param user The user profile object.
|
|
* @param addressData The address data to upsert.
|
|
* @returns The ID of the upserted address.
|
|
*/
|
|
async upsertUserAddress(user: UserProfile, addressData: Partial<Address>): Promise<number> {
|
|
return db.withTransaction(async (client) => {
|
|
// Instantiate repositories with the transactional client
|
|
const addressRepo = new AddressRepository(client);
|
|
const userRepo = new UserRepository(client);
|
|
|
|
const addressId = await addressRepo.upsertAddress({ ...addressData, address_id: user.address_id ?? undefined });
|
|
|
|
// If the user didn't have an address_id before, update their profile to link it.
|
|
if (!user.address_id) {
|
|
await userRepo.updateUserProfile(user.user_id, { address_id: addressId });
|
|
}
|
|
|
|
return addressId;
|
|
});
|
|
}
|
|
}
|
|
|
|
export const userService = new UserService(); |