-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitems.js
More file actions
86 lines (70 loc) · 1.9 KB
/
items.js
File metadata and controls
86 lines (70 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// src/items.js
import { supabase } from "./supabaseClient.js";
export async function loadItems() {
const { data, error } = await supabase
.from("items")
.select("*, owner:profiles(username), image_url")
.eq("status", "available")
.order("created_at", { ascending: false });
if (error) {
console.error(error);
return [];
}
return data;
}
/* UPLOAD FUNCTION */
export async function uploadImage(file) {
if (!file) return null;
const fileExt = file.name.split('.').pop();
const fileName = `${Date.now()}-${Math.random().toString(36).substring(2)}.${fileExt}`;
// Upload to 'item-images' bucket
const { data, error } = await supabase.storage
.from('item-images')
.upload(fileName, file);
if (error) {
console.error("Error uploading image:", error);
return null;
}
// Get Public URL
const { data: publicURL } = supabase.storage
.from('item-images')
.getPublicUrl(fileName);
return publicURL.publicUrl;
}
/* DELETE FUNCTION */
export async function deleteItem(itemId) {
const { error } = await supabase
.from("items")
.delete()
.eq("id", itemId);
if (error) {
console.error("Error deleting item:", error);
alert("Error deleting item: " + error.message);
return false;
}
return true;
}
export async function addItem(item) {
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
alert("You must be logged in to list an item.");
window.location.href = "index.html";
return null;
}
const itemWithOwner = {
...item,
image_url: item.image_url || null,
owner_id: user.id,
created_at: new Date()
};
const { data, error } = await supabase
.from("items")
.insert([itemWithOwner])
.select()
.single();
if (error) {
alert(error.message);
return null;
}
return data;
}