Skip to content

File upload #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/app/api/items/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export async function GET(request: NextRequest, response: NextResponse) {
);
}

const items = await prisma.category.findUnique({
const categoryItems = await prisma.category.findUnique({
where: {
id: id,
},
Expand All @@ -28,9 +28,9 @@ export async function GET(request: NextRequest, response: NextResponse) {
},
});

const allItems = items?.categoryItems.map((ci) => ci.Item);
const items = categoryItems?.categoryItems.map((ci) => ci.Item);

return NextResponse.json({ allItems }, { status: 200 });
return NextResponse.json({ items }, { status: 200 });
} catch (error: any) {
return NextResponse.json({ error: error.message }, { status: 400 });
}
Expand Down
15 changes: 9 additions & 6 deletions src/app/createStore/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import Button from "@/components/Button";
import TextInput from "@/components/TextInput";
import APICaller from "@/utils/APICaller";
import { loaderToast } from "@/utils/loaderToast";
import { uploadFile } from "@/utils/uploadFile";
import { useStoreRedirect } from "@/utils/useStoreRedirect";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useState } from "react";
import toast from "react-hot-toast";

export default function CreateStore() {
Expand All @@ -31,13 +32,15 @@ export default function CreateStore() {
}

loaderToast(
() =>
APICaller("/api/store", "POST", {
async () => {
const url = await uploadFile(image);

await APICaller("/api/store", "POST", {
name,
description,
image:
"https://dbdzm869oupei.cloudfront.net/img/vinylrugs/preview/26956.png",
}),
image: url,
});
},
{
success: "Restaurante criado com sucesso!",
loading: "Criando restaurante...",
Expand Down
20 changes: 3 additions & 17 deletions src/app/home/[menuId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import { Fragment, useEffect, useState } from "react";
import ResponsiveGrid from "@/components/ResponsiveGrid";
import ChevronLeftIcon from "@/assets/ChevronLeftIcon";
import { useRouter } from "next/navigation";
import ItemWithImage from "@/interfaces/ItemWIthImage";
import ItemCard from "@/app/items/ItemCard";
import { getImage } from "@/utils/R2";
import { Skeletons } from "@/components/Skeleton";

interface MenuItemParams {
Expand All @@ -19,7 +17,7 @@ export default function MenuItem({ params }: { params: MenuItemParams }) {
null
);
const [categories, setCategories] = useState<Category[] | null>();
const [items, setItems] = useState<ItemWithImage[] | null>(null);
const [items, setItems] = useState<Item[] | null>(null);

async function getCategories() {
try {
Expand All @@ -41,21 +39,9 @@ export default function MenuItem({ params }: { params: MenuItemParams }) {
try {
const response = await APICaller(
`/api/items?categoryId=${selectedCategory.id}`,
"GET",
{}
"GET"
);
const items: Item[] = response.allItems;
const map = new Map<string, File | Blob>();
const imagePromises = items.map(async (item) => {
const image = await getImage(item.image);
map.set(item.id, image);
});

Promise.all(imagePromises).then(() => {
setItems(
items.map((item) => ({ ...item, imageFile: map.get(item.id)! }))
);
});
setItems(response.items);
} catch (error) {
console.error("Erro ao buscar os menus:", error);
}
Expand Down
9 changes: 3 additions & 6 deletions src/app/items/ItemCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { NumericFormat } from "react-number-format";
import ThreeDotsIcon from "@/assets/ThreeDotsIcon";
import { Fragment } from "react";
import DropdownContextMenu from "@/components/DropdownContextMenu";
import ItemWithImage from "@/interfaces/ItemWIthImage";
import { Item } from "@prisma/client";

export default function ItemCard({
item,
onEdit,
onDelete,
onSelectCategories,
}: {
item: ItemWithImage;
item: Item;
onEdit?: () => void;
onDelete?: () => void;
onSelectCategories?: () => void;
Expand Down Expand Up @@ -40,10 +40,7 @@ export default function ItemCard({
className="rounded shadow-md bg-white p-4 flex gap-4 w-96"
>
<div className="w-24 h-24 rounded-sm overflow-hidden">
<img
className="h-full w-full"
src={URL.createObjectURL(item.imageFile)}
></img>
<img className="h-full w-full" src={item.image}></img>
</div>
<div className="flex flex-col flex-1 justify-between">
<div>
Expand Down
21 changes: 3 additions & 18 deletions src/app/items/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,41 +9,27 @@ import ConfirmDecisionModal from "@/components/ConfirmDecisionModal";
import EditItemModal from "@/components/itemModals/EditItemModal";
import ItemCard from "./ItemCard";
import CreateItemModal from "@/components/itemModals/CreateItemModal";
import { deleteImage, getImage } from "@/utils/R2";
import ItemWithImage from "@/interfaces/ItemWIthImage";
import { Skeletons } from "@/components/Skeleton";
import { loaderToast } from "@/utils/loaderToast";

export default function Items() {
const [selectedItemEdit, setSelectedItemEdit] =
useState<ItemWithImage | null>(null);
const [selectedItemDelete, setSelectedItemDelete] = useState<Item | null>(
null
);
const [selectedItemEdit, setSelectedItemEdit] = useState<Item | null>(null);
const [selectedItemSelectCategories, setSelectedItemSelectCategories] =
useState<Item | null>(null);
const [isOpenCreateItem, setIsOpenCreateItem] = useState(false);

const [items, setItems] = useState<ItemWithImage[] | null>();
const [items, setItems] = useState<Item[] | null>();
useEffect(() => {
getItems();
}, []);

async function getItems() {
try {
const response = await APICaller("/api/allItems", "GET", {});
const items: Item[] = response.allItems;
const map = new Map<string, File | Blob>();
const imagePromises = items.map(async (item) => {
const image = await getImage(item.image);
map.set(item.id, image);
});

Promise.all(imagePromises).then(() => {
setItems(
items.map((item) => ({ ...item, imageFile: map.get(item.id)! }))
);
});
setItems(response.allItems);
} catch (error) {
console.error("Erro ao buscar os menus:", error);
}
Expand All @@ -55,7 +41,6 @@ export default function Items() {
success: "Item Excluído com sucesso!",
error: "Erro ao excluir item!",
onSuccess: () => {
deleteImage(item.image);
getItems();
},
});
Expand Down
30 changes: 16 additions & 14 deletions src/app/login/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,24 @@ export default function Login() {
}
try {
const requestData = { email, password };
const method = async () => {
const response = await APICaller("/api/login", "POST", requestData);
if (!response.success) {
throw new Error("Usuário ou senha inválidos");
}
localStorage.setItem("token", response.token);
};

loaderToast(method, {
success: "Login realizado com sucesso!",
loading: "Fazendo login...",
error: "Usuário ou senha inválidos",
onSuccess: () => {
router.push("/home");
loaderToast(
async () => {
const response = await APICaller("/api/login", "POST", requestData);
if (!response.success) {
throw new Error("Usuário ou senha inválidos");
}
localStorage.setItem("token", response.token);
},
});
{
success: "Login realizado com sucesso!",
loading: "Fazendo login...",
error: "Usuário ou senha inválidos",
onSuccess: () => {
router.push("/home");
},
}
);
} catch (error) {
console.error("Erro ao fazer login:", error);
}
Expand Down
11 changes: 4 additions & 7 deletions src/components/itemModals/CreateItemModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import NumberInput from "@/components/NumberInput";
import TextInput from "@/components/TextInput";
import APICaller from "@/utils/APICaller";
import { loaderToast } from "@/utils/loaderToast";
import { pushImage } from "@/utils/R2";
import { uploadFile } from "@/utils/uploadFile";
import { useState } from "react";
import toast from "react-hot-toast";

Expand Down Expand Up @@ -68,19 +68,16 @@ export default function CreateItemModal({
}

async function postItem() {
const pushOptions = await pushImage(image!);
const url = await uploadFile(image!);
const requestData = {
description,
price,
shortDescription,
name,
internalDescription,
image: pushOptions.fileName,
image: url,
};
const response = await APICaller("/api/item", "POST", requestData);
if (response.success) {
await pushOptions.uploadFile();
}
await APICaller("/api/item", "POST", requestData);
}
return (
<Modal isOpen={isOpen} onClose={onClose}>
Expand Down
21 changes: 6 additions & 15 deletions src/components/itemModals/EditItemModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import Button from "@/components/Button";
import Modal from "@/components/Modal";
import NumberInput from "@/components/NumberInput";
import TextInput from "@/components/TextInput";
import ItemWithImage from "@/interfaces/ItemWIthImage";
import APICaller from "@/utils/APICaller";
import { loaderToast } from "@/utils/loaderToast";
import { deleteImage, pushImage } from "@/utils/R2";
import { uploadFile } from "@/utils/uploadFile";
import { Item } from "@prisma/client";
import { Fragment, useState } from "react";
import toast from "react-hot-toast";

Expand All @@ -16,7 +16,7 @@ export default function EditItemModal({
onClose,
updateItems,
}: {
item: ItemWithImage;
item: Item;
isOpen: boolean;
onClose: () => void;
updateItems: () => void;
Expand Down Expand Up @@ -62,9 +62,7 @@ export default function EditItemModal({
}

async function patchItem() {
const pushOptions = image
? await pushImage(image)
: { fileName: item.image, uploadFile: async () => {} };
const url = image ? await uploadFile(image) : item.image;

const requestData = {
id: item.id,
Expand All @@ -73,17 +71,10 @@ export default function EditItemModal({
shortDescription,
name,
internalDescription,
image: pushOptions.fileName,
image: url,
};

const response = await APICaller("/api/item", "PATCH", requestData);
if (!response.success) {
return;
}
if (image) {
await pushOptions.uploadFile();
await deleteImage(item.image);
}
await APICaller("/api/item", "PATCH", requestData);
}

return (
Expand Down
5 changes: 0 additions & 5 deletions src/interfaces/ItemWIthImage.ts

This file was deleted.

19 changes: 19 additions & 0 deletions src/utils/uploadFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export async function uploadFile(file: File) {
const formData = new FormData();
formData.append("file", file!);

try {
throw new Error("Not implemented");
const response = await fetch(
`${process.env.NEXT_PUBLIC_FILE_UPLOAD_PATH}/api/uploadFile`,
{
method: "POST",
body: formData,
}
);
const data = await response.json();
return data.url;
} catch (error) {
return "https://occ-0-8407-2219.1.nflxso.net/dnm/api/v6/LmEnxtiAuzezXBjYXPuDgfZ4zZQ/AAAABf9HCQwc6Epz3CArWHNpM-yiybdhZPyg5w47F_0HLHLrufr65Chh-G9s2St_VimDQMhclKLrKaGn0LZfAiv8kdrPNgaYF2Gju5iIIgWaQChx.png?r=73a";
}
}