Skip to content
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@ yarn-error.log*
next-env.d.ts
#model folder
/public/models
(test)
(test)
.vscode
107 changes: 107 additions & 0 deletions app/admin/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
"use client";

import { useForm } from "react-hook-form";
import axios from "axios";
import { useEffect, useState } from "react";
import Image from "next/image";

function Card({ details }) {
return (
<div className="max-w-sm rounded overflow-hidden shadow-lg">
<Image
height={100}
width={100}
src={details.thumbnail}
alt="Card Image"
className="w-full"
/>
<div className="px-6 py-4">
<p className="font-bold text-xl mb-2">{details.name}</p>
</div>
</div>
);
}
const UploadModel = () => {
const {
register,
handleSubmit,
setError,
formState: { errors },
} = useForm();
const [data, setData] = useState([]);

const onSubmit = async ({ name, isPublished, thumbnail, _3dmodel }) => {
const formData = new FormData();
// console.log(thumbnail[0]);
// return;
formData.append("data", JSON.stringify({ name, isPublished }));
formData.append("thumbnail", thumbnail[0]);
formData.append("_3dmodel", _3dmodel[0]);
try {
const response = await axios.post("/api/3dmodels", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});

if (response.status === 201) {
console.log("Data saved successfully");
console.log(response.data.savedData);
setData((prev) => [...prev, response.data.savedData]);
} else {
console.error("Failed to save data:", response.statusText);
}
} catch (error) {
console.error("Error:", error.message);
}
};

async function getData() {
const data = await axios.get("/api/3dmodels");

setData(data.data);
console.log(data.data);
}
useEffect(() => {
getData();
}, []);

return (
<div className="container mx-auto p-4">
<form className="flex flex-col m-4" onSubmit={handleSubmit(onSubmit)}>
<label>Name:</label>
<input {...register("name", { required: "Name is required" })} />
{errors.name && <p>{errors.name.message}</p>}

<label>Publish:</label>
<input
type="checkbox"
{...register("isPublished", {
required: "Publish status is required",
})}
/>
{errors.isPublished && <p>{errors.name.message}</p>}

<label>Thumbnail:</label>
<input
type="file"
{...register("thumbnail", { required: "Thumbnail is required" })}
/>
{errors.thumbnail && <p>{errors.thumbnail.message}</p>}

<input
type="file"
{...register("_3dmodel", { required: "_3dmodel is required" })}
/>
{errors._3dmodel && <p>{errors._3dmodel.message}</p>}

<button type="submit">Submit</button>
</form>
{data.map((item) => (
<Card key={item._id} details={item} />
))}
</div>
);
};

export default UploadModel;
66 changes: 66 additions & 0 deletions app/api/3dmodels/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { NextResponse } from "next/server";
import connectToDB from "@/dbconfigs/connect";
import ThreeDModels from "@/db_models/3dmodels";
import uploadFileToS3 from "@/utils/fileUploads3";

async function uploadedFileToBuffer(files) {
const buffers = await Promise.all(
files.map(async (file) => {
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes);
return buffer;
})
);

return buffers;
}

export async function POST(req, res) {
try {
await connectToDB();
const formData = await req.formData();
console.log(formData.get("data"));
console.log(formData.get("thumbnail"));
const files = [formData.get("thumbnail"), formData.get("_3dmodel")];
const buffers = await uploadedFileToBuffer(files);
const fileToFolder = ["model_thumbnails", "models"];
const [thumb_url, _3dmodel_url] = await Promise.all(
buffers.map(
async (buffer, i) =>
await uploadFileToS3(buffer, { folderName: fileToFolder[i] })
)
);

const { name, isPublished } = JSON.parse(formData.get("data"));
console.log(name);
const savedData = await ThreeDModels.create({
name,
size: formData.get("thumbnail").size / 1024, //coverting to KB
js_file: "path",
thumbnail: thumb_url,
_3dmodel: _3dmodel_url,
isPublished,
});

return NextResponse.json(
{ message: "Data saved successfully", savedData },
{ status: 201 }
);
} catch (error) {
console.error("Error saving data:", error);
return NextResponse.json({ message: "ERROR: ISE" }, { status: 500 });
}
}

export async function GET() {
try {
await connectToDB();
// Get all the records in the table
let models = await ThreeDModels.find();
console.log(models);
return NextResponse.json([...models], { status: 200 });
} catch (err) {
console.log(err);
return NextResponse.json({ message: "ERROR: ISE" }, { status: 500 });
}
}
40 changes: 40 additions & 0 deletions db_models/3dmodels.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import mongoose from "mongoose";

const three_d_model = new mongoose.Schema({
name: {
type: String,
required: true,
},
size: {
type: Number,
required: true,
},
date_created: {
type: Date,
default: Date.now,
},
js_file: {
type: String,
required: true,
},
thumbnail: {
type: String,
// You might want to add validation or default values for thumbnails
},
_3dmodel: {
type: String,
// You might want to add validation or default values for thumbnails
},
isPublished: {
type: Boolean,
},
});
console.log(mongoose.models.three_d_model);
if (mongoose.models.three_d_model)
console.log("The model already existed, hence no model created!!");
else console.log("Need to create a model!!!");
const ThreeDModels =
mongoose.models.three_d_model ||
mongoose.model("three_d_model", three_d_model);

export default ThreeDModels;
10 changes: 10 additions & 0 deletions dbconfigs/connect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import mongoose from "mongoose";

export default async function connectToDB() {
try {
await mongoose.connect(process.env.mongdb_con_str);
console.log("connected successfully");
} catch (err) {
console.log("error" + err.message);
}
}
8 changes: 6 additions & 2 deletions next.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
/** @type {import('next').NextConfig} */
const nextConfig = {}
const nextConfig = {
images: {
domains: ["eway-models.s3.ap-south-1.amazonaws.com"],
},
};

module.exports = nextConfig
module.exports = nextConfig;
38 changes: 38 additions & 0 deletions utils/fileUploads3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const fs = require("fs");

const { Upload } = require("@aws-sdk/lib-storage");
const { S3 } = require("@aws-sdk/client-s3");

export default async function uploadFileToS3(
fileBuffer,
{ folderName, fileName }
) {
// Create an S3 instance
const s3 = new S3({
credentials: {
accessKeyId: process.env.AWS_S3_ACCESS_KEY,
secretAccessKey: process.env.AWS_S3_SECRET_ACCESS_KEY,
},

region: process.env.AWS_S3_REGION,
});

// Specify the S3 bucket and file information
const bucketName = "eway-models";

// Set S3 upload parameters

const params = {
Bucket: bucketName,
Key: `${folderName}/${fileName || Date.now()}`,
Body: fileBuffer,
ACL: "public-read", // Set ACL as needed
};

const uploaded = await new Upload({
client: s3,
params,
}).done();
console.log(uploaded.Location);
return uploaded.Location;
}