export const products = {
create: defineAction({
accept: "form",
input: z.object({
name: z.string(),
description: z.string(),
category: z.string(),
amount: z.number(),
image: z.instanceof(File).optional(),
}),
handler: async ({ name, description, category, amount, image }, ctx) => {
try {
// call to api to create product with the form inputs, and return `product_id`
let imageUrl = null;
if (image && image.size > 0) {
const fileExtension = image.name.split(".").pop();
const fileName = `${product_id}.${fileExtension}`;
await ctx.locals.runtime.env.CB_BUCKET.put(fileName, image);
imageUrl = `https://example.com/${fileName}`;
console.log("Image uploaded:", imageUrl);
}
return {
success: true,
message: "Product added successfully",
id: product_id,
};
} catch (error: unknown) {
console.error("Error adding a product", error);
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
return {
success: false,
message: `Failed to add product: ${errorMessage}`,
};
}
},
}),
};
export const products = {
create: defineAction({
accept: "form",
input: z.object({
name: z.string(),
description: z.string(),
category: z.string(),
amount: z.number(),
image: z.instanceof(File).optional(),
}),
handler: async ({ name, description, category, amount, image }, ctx) => {
try {
// call to api to create product with the form inputs, and return `product_id`
let imageUrl = null;
if (image && image.size > 0) {
const fileExtension = image.name.split(".").pop();
const fileName = `${product_id}.${fileExtension}`;
await ctx.locals.runtime.env.CB_BUCKET.put(fileName, image);
imageUrl = `https://example.com/${fileName}`;
console.log("Image uploaded:", imageUrl);
}
return {
success: true,
message: "Product added successfully",
id: product_id,
};
} catch (error: unknown) {
console.error("Error adding a product", error);
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
return {
success: false,
message: `Failed to add product: ${errorMessage}`,
};
}
},
}),
};