Skip to content

Commit

Permalink
changes in middleware and api
Browse files Browse the repository at this point in the history
  • Loading branch information
KirtanTank committed Aug 16, 2024
1 parent c91f90c commit d75bfbe
Show file tree
Hide file tree
Showing 7 changed files with 87 additions and 47 deletions.
5 changes: 5 additions & 0 deletions models/Vendor.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ const VendorSchema = new mongoose.Schema({
type: String,
required:true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
}
}, {timestamps: true});

mongoose.models = {}
Expand Down
6 changes: 3 additions & 3 deletions pages/_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import {SessionProvider} from 'next-auth/react';

function MyApp({ Component, pageProps, session }) {
return (
<>
<div className='bg-[#BEFEA8] min-w-full min-h-screen'>
<SessionProvider session={session}>
<div className='flex flex-col gap-5 mb-7'>
<div className='flex flex-col gap-5 w-full h-full'>
<Navbar />
<Component {...pageProps} />
</div>
</SessionProvider>
</>
</div>
);
}

Expand Down
1 change: 0 additions & 1 deletion pages/api/addVendors.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import connectDb from '../../middleware/mongoose';

const handler = async (req, res) => {
if(req.method == 'POST'){
// console.log(req.body);
let v = new Vendor(req.body);
await v.save();
res.status(200).json({ success: "success" })
Expand Down
36 changes: 32 additions & 4 deletions pages/api/auth/[...nextauth].js
Original file line number Diff line number Diff line change
@@ -1,12 +1,40 @@
import NextAuth from 'next-auth/next'
import GoogleProvider from 'next-auth/providers/google'
import NextAuth from 'next-auth';
import connectDb from '../../../middleware/mongoose';
import GoogleProvider from 'next-auth/providers/google';
import User from '../../../models/User';

export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
secret: process.env.JWT_SECRET
secret: process.env.JWT_SECRET,
callbacks: {
async jwt({ token, account, profile }) {
await connectDb();

if (account && profile) {
let existingUser = await User.findOne({ email: profile.email });

if (!existingUser) {
existingUser = new User({
name: profile.name,
email: profile.email,
});
await existingUser.save();
}

token.userId = existingUser._id;
}

return token;
},
async session({ session, token }) {
session.userId = token.userId;
return session;
},
},

});
9 changes: 7 additions & 2 deletions pages/api/getVendors.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ import connectDb from "../../middleware/mongoose";

const handler = async (req, res) => {
if (req.method == "GET") {
let vendors = await Vendor.find();
res.status(200).json({ vendors });
try {
let vendors = await Vendor.find({ userId: req.query.userId });
res.status(200).json({ vendors });
} catch (error) {
res.status(500).json({ error: "Error fetching vendors" });
}
} else {
res.status(400).json({ error: "This method is not allowed" });
}
};

export default connectDb(handler);

75 changes: 39 additions & 36 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import "react-toastify/dist/ReactToastify.css";
import EditVendorModal from "../components/EditVendorModal";
import VendorCard from "../components/VendorCard";
import DeleteVendorModal from "../components/DeleteVendorModal";
import { useSession } from "next-auth/react";

var updatedDetailsOfVendors = [];
const Index = () => {
// console.log(vendors);
const [vendors, setVendors] = useState([]);
const [_id, setId] = useState("");
const [name, setName] = useState("");
Expand All @@ -23,19 +23,23 @@ const Index = () => {
// Pagination
const [totalVendors, setTotalVendors] = useState(vendors.length);
const [currentPage, setCurrentPage] = useState(1);
const [vendorsPerPage] = useState(10);
const [vendorsPerPage] = useState(6);

const [openDeleteModal, setOpenDeleteModal] = useState(false);
const [vendorToBeDelete, setVendorToBeDelete] = useState("");

const { data: session } = useSession();
const userId = session?.userId;

useEffect(() => {
if(!userId) return;
fetchVendors();
}, []);
}, [userId]);

// Get Request
const fetchVendors = async () => {
try {
const response = await fetch("/api/getVendors", {
const response = await fetch(`/api/getVendors?userId=${userId}`, {
method: "GET",
});

Expand Down Expand Up @@ -77,40 +81,39 @@ const Index = () => {

const paginate = (pageNumber) => setCurrentPage(pageNumber);
return (
<div className="position-relative">
<VendorCard
editFun={editFun}
currentVendors={currentVendors}
setOpenDeleteModal={setOpenDeleteModal}
setVendorToBeDelete={setVendorToBeDelete}
/>

{showEditVendorModal && (
<EditVendorModal
_id={_id}
accNo={accNo}
setAccNo={setAccNo}
address1={address1}
setAddress1={setAddress1}
address2={address2}
setAddress2={setAddress2}
bankName={bankName}
setBankName={setBankName}
city={city}
setCity={setCity}
country={country}
setCountry={setCountry}
name={name}
setName={setName}
zipCode={zipCode}
setZipCode={setZipCode}
updatedDetailsOfVendors={updatedDetailsOfVendors}
setShowEditVendorModal={setShowEditVendorModal}
fetchVendors={fetchVendors}
<div className="relative flex flex-col min-h-full">
<VendorCard
editFun={editFun}
currentVendors={currentVendors}
setOpenDeleteModal={setOpenDeleteModal}
setVendorToBeDelete={setVendorToBeDelete}
/>
)}

<div className="flex justify-center absolute bottom-0 w-full z-[-10]">
<EditVendorModal
showEditVendorModal={showEditVendorModal}
_id={_id}
accNo={accNo}
setAccNo={setAccNo}
address1={address1}
setAddress1={setAddress1}
address2={address2}
setAddress2={setAddress2}
bankName={bankName}
setBankName={setBankName}
city={city}
setCity={setCity}
country={country}
setCountry={setCountry}
name={name}
setName={setName}
zipCode={zipCode}
setZipCode={setZipCode}
updatedDetailsOfVendors={updatedDetailsOfVendors}
setShowEditVendorModal={setShowEditVendorModal}
fetchVendors={fetchVendors}
/>

<div className="flex justify-center w-full mt-5">
<Pagination
vendorsPerPage={vendorsPerPage}
totalVendors={totalVendors}
Expand Down
2 changes: 1 addition & 1 deletion pages/vendor.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import VendorComp from "../components/Vendor";
import VendorComp from "../components/AddVendor";

const Vendor = () => {
return (
Expand Down

0 comments on commit d75bfbe

Please sign in to comment.