Files
Fastchat/utils/assets/avatars.ts
T

76 lines
2.0 KiB
TypeScript

"use server";
import { createClient } from "@/utils/supabase/server";
/**
* Generate a signed URL for a user's avatar from Supabase storage.
* The bucket is private, so signed URLs are required to access avatars.
*
* @param userId - The user ID whose avatar to fetch
* @param expiresIn - URL expiry in seconds (default: 1 hour)
* @returns Signed URL string, or null if not found/error
*/
export async function getSignedAvatarUrl(
userId: string,
expiresIn: number = 3600,
): Promise<string | null> {
const supabase = await createClient();
const { data, error } = await supabase.storage
.from("avatars")
.createSignedUrl(`${userId}/avatar`, expiresIn);
if (error || !data?.signedUrl) {
return null;
}
return data.signedUrl;
}
/**
* Generate signed avatar URLs for multiple users at once.
* Returns a Map of userId -> signedUrl (null if no avatar).
*
* @param userIds - Array of user IDs
* @param expiresIn - URL expiry in seconds (default: 1 hour)
*/
export async function getSignedAvatarUrls(
userIds: string[],
expiresIn: number = 3600,
): Promise<Map<string, string | null>> {
const result = new Map<string, string | null>();
if (userIds.length === 0) return result;
const supabase = await createClient();
// Build the paths for all users
const paths = userIds.map((id) => `${id}/avatar`);
// createSignedUrl supports an array of paths
const { data, error } = await supabase.storage
.from("avatars")
.createSignedUrls(paths, expiresIn);
if (error || !data) {
// Fallback: return null for all
for (const id of userIds) {
result.set(id, null);
}
return result;
}
// data is an array of { path, signedUrl } or { path, error }
const urlByPath = new Map<string, string | null>();
for (const item of data) {
if (item.path) {
urlByPath.set(item.path, item.signedUrl ?? null);
}
}
for (const id of userIds) {
result.set(id, urlByPath.get(`${id}/avatar`) ?? null);
}
return result;
}