diff --git a/prisma/schema.prisma b/prisma/schema.prisma index b7febd1..220a715 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -91,7 +91,6 @@ model UserAddress { // Relaciones country Country @relation(fields: [countryId], references: [id]) countryId String - - user User @relation(fields: [userId], references: [id]) - userId String @unique + user User @relation(fields: [userId], references: [id]) + userId String @unique } diff --git a/src/actions/address/set-user-address.ts b/src/actions/address/set-user-address.ts new file mode 100644 index 0000000..4dbdbdc --- /dev/null +++ b/src/actions/address/set-user-address.ts @@ -0,0 +1,52 @@ +'use server'; + +import type { Address } from '@/interfaces/address.interface'; +import prisma from '@/lib/prisma'; + +export const setUserAddress = async (address: Address, userId: string) => { + try { + const newAddress = await createOrReplaceAddress(address, userId); + + return { + ok: true, + address: newAddress, + message: 'Dirección guardada', + }; + } catch (error) { + console.log(error); + return { + ok: false, + message: 'Error al guardar la dirección', + }; + } +}; + +const createOrReplaceAddress = async (address: Address, userId: string) => { + try { + const storedAddress = await prisma.userAddress.findFirst({ where: { userId } }); + const { rememberAddress, country, address2 = '', ...data } = address; + + const addressToSave = { + ...data, + address2, + countryId: country, + userId, + }; + + if (!storedAddress) { + const newAddress = await prisma.userAddress.create({ + data: addressToSave, + }); + return newAddress; + } + + const updatedAddress = await prisma.userAddress.update({ + where: { id: storedAddress.id }, + data: addressToSave, + }); + return updatedAddress; + } catch (error) { + console.log(error); + throw new Error('Error al crear o reemplazar la dirección'); + } +}; diff --git a/src/interfaces/address.interface.ts b/src/interfaces/address.interface.ts new file mode 100644 index 0000000..d581fc6 --- /dev/null +++ b/src/interfaces/address.interface.ts @@ -0,0 +1,11 @@ +export interface Address { + firstName: string; + lastName: string; + address: string; + address2?: string; + postalCode: string; + city: string; + country: string; + phone: string; + rememberAddress: boolean; +}