forked from Movalabs-crew/mova-store
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproducts.js
More file actions
83 lines (69 loc) · 2.08 KB
/
Copy pathproducts.js
File metadata and controls
83 lines (69 loc) · 2.08 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
import { supabase } from "./supabase";
import { PRODUCTS_TABLE, PRODUCTS_BUCKET } from "./collections";
/**
* Normalize a products row for the UI.
*/
export function mapProduct(row) {
if (!row) return null;
return {
id: row.id,
name: row.name,
price: Number(row.price),
img: row.img,
created_at: row.created_at,
};
}
export async function listProducts() {
const { data, error } = await supabase
.from(PRODUCTS_TABLE)
.select("*")
.order("created_at", { ascending: false });
if (error) throw new Error(error.message);
return (data || []).map(mapProduct);
}
export async function getProductById(id) {
const { data, error } = await supabase
.from(PRODUCTS_TABLE)
.select("*")
.eq("id", id)
.maybeSingle();
if (error) throw new Error(error.message);
return mapProduct(data);
}
export async function uploadProductImage(file) {
const ext = file.name.split(".").pop() || "jpg";
const path = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
const { error: uploadError } = await supabase.storage
.from(PRODUCTS_BUCKET)
.upload(path, file, {
cacheControl: "3600",
upsert: false,
contentType: file.type || "image/jpeg",
});
if (uploadError) throw new Error(uploadError.message);
const { data } = supabase.storage.from(PRODUCTS_BUCKET).getPublicUrl(path);
return data.publicUrl;
}
export async function createProduct({ name, price, img }) {
const { data, error } = await supabase
.from(PRODUCTS_TABLE)
.insert([{ name, price, img }])
.select()
.single();
if (error) throw new Error(error.message);
return mapProduct(data);
}
export async function updateProduct(id, { name, price, img }) {
const { data, error } = await supabase
.from(PRODUCTS_TABLE)
.update({ name, price, img })
.eq("id", id)
.select()
.single();
if (error) throw new Error(error.message);
return mapProduct(data);
}
export async function deleteProduct(id) {
const { error } = await supabase.from(PRODUCTS_TABLE).delete().eq("id", id);
if (error) throw new Error(error.message);
}