|
1 | 1 | "use server";
|
2 | 2 |
|
3 |
| -import type { Resource } from "@/types"; |
| 3 | +import type { |
| 4 | + CreateResourceInput, |
| 5 | + UpdateResourceInput, |
| 6 | + Resource, |
| 7 | +} from "@/types"; |
4 | 8 |
|
5 | 9 | import { createClient } from "@/lib/supabase/server";
|
6 | 10 |
|
@@ -32,3 +36,48 @@ export const getResourceBySlug = async (
|
32 | 36 | if (error) throw new Error(error.message);
|
33 | 37 | return data;
|
34 | 38 | };
|
| 39 | + |
| 40 | +export const createResource = async (input: CreateResourceInput) => { |
| 41 | + const supabase = await createClient(); |
| 42 | + const { data: userData, error: userError } = await supabase.auth.getUser(); |
| 43 | + if (userError || !userData?.user) throw new Error("User not found"); |
| 44 | + const { id: userId } = userData.user; |
| 45 | + const payload = { ...input, author: userId }; |
| 46 | + |
| 47 | + const { data, error } = await supabase |
| 48 | + .from("resources") |
| 49 | + .insert([payload]) |
| 50 | + .select() |
| 51 | + .single(); |
| 52 | + |
| 53 | + if (error) throw new Error(`Error creating resource: ${error.message}`); |
| 54 | + return data; |
| 55 | +}; |
| 56 | + |
| 57 | +export const updateResource = async ( |
| 58 | + id: string, |
| 59 | + input: UpdateResourceInput, |
| 60 | +) => { |
| 61 | + const supabase = await createClient(); |
| 62 | + |
| 63 | + const { data, error } = await supabase |
| 64 | + .from("resources") |
| 65 | + .update(input) |
| 66 | + .eq("id", id) |
| 67 | + .select() |
| 68 | + .single(); |
| 69 | + |
| 70 | + if (error) throw new Error(`Error updating resource: ${error.message}`); |
| 71 | + return data; |
| 72 | +}; |
| 73 | + |
| 74 | +export async function getUserResources(userId: string) { |
| 75 | + const supabase = await createClient(); |
| 76 | + const { data, error } = await supabase |
| 77 | + .from("resources") |
| 78 | + .select(`*, category:categories (id, name)`) |
| 79 | + .eq("author", userId); |
| 80 | + |
| 81 | + if (error) throw new Error(`Error fetching resources: ${error.message}`); |
| 82 | + return data; |
| 83 | +} |
0 commit comments