Skip to content

Commit

Permalink
agrega server actions de la direccion
Browse files Browse the repository at this point in the history
  • Loading branch information
Lostovayne committed Oct 29, 2024
1 parent 01743a6 commit 3185c26
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 3 deletions.
5 changes: 2 additions & 3 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
52 changes: 52 additions & 0 deletions src/actions/address/set-user-address.ts
Original file line number Diff line number Diff line change
@@ -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');
}
};
11 changes: 11 additions & 0 deletions src/interfaces/address.interface.ts
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit 3185c26

Please sign in to comment.