Skip to content

Commit

Permalink
latest changes
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianhajdin committed May 5, 2023
1 parent 9d7b6c6 commit 44be0ff
Show file tree
Hide file tree
Showing 18 changed files with 464 additions and 379 deletions.
42 changes: 19 additions & 23 deletions app/api/auth/[...nextauth]/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,39 +13,35 @@ const handler = NextAuth({
],
callbacks: {
async session({ session }) {
const sessionUser = await User.findOne({
email: session.user.email
})

// store the user id from MongoDB to session
const sessionUser = await User.findOne({ email: session.user.email });
session.user.id = sessionUser._id.toString();

return session;
},
async signIn({ profile }) {
try {
async signIn({ account, profile, user, credentials }) {
try {
await connectToDB();

// check if a user already exists
const userExists = await User.findOne({
email: profile.email
});

// if not, create a new user
if(!userExists) {

// check if user already exists
const userExists = await User.findOne({ email: profile.email });

// if not, create a new document and save user in MongoDB
if (!userExists) {
await User.create({
email: profile.email,
username: profile.name.replace(" ", "").toLowerCase(),
image: profile.picture
})
image: profile.picture,
});
}
return true;

return true
} catch (error) {
console.log(error);
return false;
console.log("Error checking if user exists: ", error.message);
return false
}
}
},
}
})

export { handler as GET, handler as POST };
export { handler as GET, handler as POST }
71 changes: 37 additions & 34 deletions app/api/prompt/[id]/route.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,54 @@
import { connectToDB } from '@utils/database';
import Prompt from '@models/prompt';
import Prompt from "@models/prompt";
import { connectToDB } from "@utils/database";

// GET (read)
export const GET = async (request, { params }) => {
try {
await connectToDB();
try {
await connectToDB()

const prompt = await Prompt.findById(params.id).populate('creator');
if(!prompt) return new Response("Prompt not found", { status: 404 })
const prompt = await Prompt.findById(params.id).populate("creator")
if (!prompt) return new Response("Prompt Not Found", { status: 404 });

return new Response(JSON.stringify(prompt), { status: 200 })
} catch (error) {
return new Response("Failed to fetch all prompts", { status: 500 })
}
return new Response(JSON.stringify(prompt), { status: 200 })

} catch (error) {
return new Response("Internal Server Error", { status: 500 });
}
}

// PATCH (update)
export const PATCH = async (request, { params }) => {
const { prompt, tag } = await request.json();
const { prompt, tag } = await request.json();

try {
await connectToDB();
try {
await connectToDB();

const existingPrompt = await Prompt.findById(params.id);
// Find the existing prompt by ID
const existingPrompt = await Prompt.findById(params.id);

if(!existingPrompt) return new Response("Prompt not found", { status: 404 })
if (!existingPrompt) {
return new Response("Prompt not found", { status: 404 });
}

existingPrompt.prompt = prompt;
existingPrompt.tag = tag;
// Update the prompt with new data
existingPrompt.prompt = prompt;
existingPrompt.tag = tag;

await existingPrompt.save();
await existingPrompt.save();

return new Response(JSON.stringify(existingPrompt), { status: 200 })
} catch (error) {
return new Response("Failed to update prompt", { status: 500 })
}
}
return new Response("Successfully updated the Prompts", { status: 200 });
} catch (error) {
return new Response("Error Updating Prompt", { status: 500 });
}
};

// DELETE (delete)
export const DELETE = async (request, { params }) => {
try {
await connectToDB();
try {
await connectToDB();

await Prompt.findByIdAndRemove(params.id);
// Find the prompt by ID and remove it
await Prompt.findByIdAndRemove(params.id);

return new Response("Prompt deleted successfully", { status: 200 })
} catch (error) {
return new Response("Failed to delete prompt", { status: 500 })
}
}
return new Response("Prompt deleted successfully", { status: 200 });
} catch (error) {
return new Response("Error deleting prompt", { status: 500 });
}
};
31 changes: 13 additions & 18 deletions app/api/prompt/new/route.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
import { connectToDB } from '@utils/database';
import Prompt from '@models/prompt';
import Prompt from "@models/prompt";
import { connectToDB } from "@utils/database";

export const POST = async (req) => {
const { userId, prompt, tag } = await req.json();
export const POST = async (request) => {
const { userId, prompt, tag } = await request.json();

try {
await connectToDB();
const newPrompt = new Prompt({
creator: userId,
prompt,
tag
})
try {
await connectToDB();
const newPrompt = new Prompt({ creator: userId, prompt, tag });

await newPrompt.save();

return new Response(JSON.stringify(newPrompt), { status: 201 })
} catch (error) {
return new Response("Failed to create a new prompt", { status: 500 })
}
}
await newPrompt.save();
return new Response(JSON.stringify(newPrompt), { status: 201 })
} catch (error) {
return new Response("Failed to create a new prompt", { status: 500 });
}
}
20 changes: 10 additions & 10 deletions app/api/prompt/route.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { connectToDB } from '@utils/database';
import Prompt from '@models/prompt';
import Prompt from "@models/prompt";
import { connectToDB } from "@utils/database";

export const GET = async (request) => {
try {
await connectToDB();
try {
await connectToDB()

const prompts = await Prompt.find({}).populate('creator');
const prompts = await Prompt.find({}).populate('creator')

return new Response(JSON.stringify(prompts), { status: 200 })
} catch (error) {
return new Response("Failed to fetch all prompts", { status: 500 })
}
}
return new Response(JSON.stringify(prompts), { status: 200 })
} catch (error) {
return new Response("Failed to fetch all prompts", { status: 500 })
}
}
22 changes: 10 additions & 12 deletions app/api/users/[id]/posts/route.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { connectToDB } from '@utils/database';
import Prompt from '@models/prompt';
import Prompt from "@models/prompt";
import { connectToDB } from "@utils/database";

export const GET = async (request, { params }) => {
try {
await connectToDB();
try {
await connectToDB()

const prompts = await Prompt.find({
creator: params.id
}).populate('creator');
const prompts = await Prompt.find({ creator: params.id }).populate("creator")

return new Response(JSON.stringify(prompts), { status: 200 })
} catch (error) {
return new Response("Failed to fetch all prompts", { status: 500 })
}
}
return new Response(JSON.stringify(prompts), { status: 200 })
} catch (error) {
return new Response("Failed to fetch prompts created by user", { status: 500 })
}
}
45 changes: 21 additions & 24 deletions app/create-prompt/page.jsx
Original file line number Diff line number Diff line change
@@ -1,54 +1,51 @@
'use client';
"use client";

import { useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

import Form from '@components/Form';
import Form from "@components/Form";

const CreatePrompt = () => {
const router = useRouter();
const { data: session } = useSession();

const [submitting, setSubmitting] = useState(false);
const [post, setPost] = useState({
prompt: '',
tag: '',
});
const [submitting, setIsSubmitting] = useState(false);
const [post, setPost] = useState({ prompt: "", tag: "" });

const createPrompt = async (e) => {
e.preventDefault();
setSubmitting(true);
setIsSubmitting(true);

try {
const response = await fetch('/api/prompt/new', {
method: 'POST',
const response = await fetch("/api/prompt/new", {
method: "POST",
body: JSON.stringify({
prompt: post.prompt,
userId: session?.user.id,
tag: post.tag
})
})
tag: post.tag,
}),
});

if(response.ok) {
router.push('/');
if (response.ok) {
router.push("/");
}
} catch (error) {
console.log(error);
} finally {
setSubmitting(false);
setIsSubmitting(false);
}
}
};

return (
<Form
type="Create"
type='Create'
post={post}
setPost={setPost}
submitting={submitting}
handleSubmit={createPrompt}
/>
)
}
);
};

export default CreatePrompt
export default CreatePrompt;
44 changes: 21 additions & 23 deletions app/layout.jsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
import '@styles/globals.css';
import "@styles/globals.css";

import Nav from '@components/Nav';
import Provider from '@components/Provider';
import Nav from "@components/Nav";
import Provider from "@components/Provider";

export const metadata = {
title: "Promptopia",
description: 'Discover & Share AI Prompts'
}
description: "Discover & Share AI Prompts",
};

const RootLayout = ({ children }) => {
return (
<html lang="en">
<body>
<Provider>
<div className="main">
<div className="gradient" />
</div>
const RootLayout = ({ children }) => (
<html lang='en'>
<body>
<Provider>
<div className='main'>
<div className='gradient' />
</div>

<main className="app">
<Nav />
{children}
</main>
</Provider>
</body>
</html>
)
}
<main className='app'>
<Nav />
{children}
</main>
</Provider>
</body>
</html>
);

export default RootLayout;
export default RootLayout;
Loading

0 comments on commit 44be0ff

Please sign in to comment.