user address
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { FilterQuery, RequiredEntityData } from '@mikro-orm/core';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UserAddress } from './entities/user-address.entity';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { FindUsersDto } from './dto/find-user.dto';
|
||||
import { CreateUserAddressDto } from './dto/create-user-address.dto';
|
||||
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
|
||||
import { UserRepository } from './repositories/user.repository';
|
||||
|
||||
@@ -137,4 +139,48 @@ export class UserService {
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getUserAddresses(userId: string): Promise<UserAddress[]> {
|
||||
const user = await this.userRepository.findOne({ id: userId }, { populate: ['addresses'] });
|
||||
if (!user) {
|
||||
throw new NotFoundException(`User with ID ${userId} not found.`);
|
||||
}
|
||||
|
||||
// Load addresses if not already loaded
|
||||
await user.addresses.loadItems();
|
||||
return user.addresses.getItems();
|
||||
}
|
||||
|
||||
async createUserAddress(userId: string, dto: CreateUserAddressDto): Promise<UserAddress> {
|
||||
const user = await this.userRepository.findOne({ id: userId });
|
||||
if (!user) {
|
||||
throw new NotFoundException(`User with ID ${userId} not found.`);
|
||||
}
|
||||
|
||||
// If setting as default, unset other default addresses
|
||||
if (dto.isDefault) {
|
||||
const existingAddresses = await this.em.find(UserAddress, { user: { id: userId }, isDefault: true });
|
||||
for (const address of existingAddresses) {
|
||||
address.isDefault = false;
|
||||
}
|
||||
await this.em.flush();
|
||||
}
|
||||
|
||||
// Create new address
|
||||
const address = this.em.create(UserAddress, {
|
||||
user,
|
||||
title: dto.title,
|
||||
address: dto.address,
|
||||
city: dto.city,
|
||||
province: dto.province,
|
||||
postalCode: dto.postalCode,
|
||||
latitude: dto.latitude,
|
||||
longitude: dto.longitude,
|
||||
phone: dto.phone,
|
||||
isDefault: dto.isDefault ?? false,
|
||||
});
|
||||
|
||||
await this.em.persistAndFlush(address);
|
||||
return address;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user