Files

108 lines
2.8 KiB
TypeScript

"use server";
import { revalidatePath } from "next/cache";
import { createClient } from "@/utils/supabase/server";
export type UpdateNameState = { error: string } | { success: true } | null;
export async function updateNameAction(
_prevState: UpdateNameState,
formData: FormData,
): Promise<UpdateNameState> {
const name = formData.get("name");
if (typeof name !== "string" || !name.trim()) {
return { error: "Name cannot be empty." };
}
const trimmed = name.trim();
if (trimmed.length > 50) {
return { error: "Name must be 50 characters or less." };
}
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return { error: "Not authenticated" };
const { error } = await supabase
.from("users")
.update({ name: trimmed })
.eq("id", user.id);
if (error) {
return { error: error.message };
}
// Update friend_alias in all friends rows where this user is the friend
// so that other users see the new display name
await supabase
.from("friends")
.update({ friend_alias: trimmed })
.eq("friend_id", user.id);
revalidatePath("/profile");
revalidatePath("/friends");
return { success: true };
}
export type UploadAvatarState = { error: string } | { success: true } | null;
export async function uploadAvatarAction(
_prevState: UploadAvatarState,
formData: FormData,
): Promise<UploadAvatarState> {
const file = formData.get("avatar");
if (!(file instanceof File) || file.size === 0) {
return { error: "Please select an image file." };
}
// Validate file type
if (file.type !== "image/png" && file.type !== "image/jpeg") {
return { error: "Only PNG and JPG images are allowed." };
}
// Validate file size (2MB)
if (file.size > 2 * 1024 * 1024) {
return { error: "Image must be smaller than 2MB." };
}
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return { error: "Not authenticated" };
const arrayBuffer = await file.arrayBuffer();
const filePath = `${user.id}/avatar`;
const { error: uploadError } = await supabase.storage
.from("avatars")
.upload(filePath, arrayBuffer, {
contentType: file.type,
upsert: true,
});
if (uploadError) {
return { error: uploadError.message };
}
// Store the storage path — signed URLs are generated on read
const avatarPath = filePath;
// Update user's avatar_url with the storage path
const { error: updateError } = await supabase
.from("users")
.update({ avatar_url: avatarPath })
.eq("id", user.id);
if (updateError) {
return { error: updateError.message };
}
revalidatePath("/profile");
revalidatePath("/friends");
revalidatePath("/rooms");
return { success: true };
}