Skip to content
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

Adidos api #11

Open
wants to merge 30 commits into
base: starter
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
5742365
creating routes and RootLayout with logo
adim806 Oct 16, 2024
26540f9
Update README.md
adim806 Oct 16, 2024
5ad358d
succ logo route (homepage,dashboard,dashboard/chats/:id
adim806 Oct 16, 2024
a695934
navigation bar custo
adim806 Oct 16, 2024
20cf0c4
auth with clerk-react. sign-in && sign-up routes with nav bar and use…
adim806 Oct 17, 2024
e4c374d
first style home page+ animation
adim806 Oct 17, 2024
9129f0a
React animated Home Design
adim806 Oct 17, 2024
e351db4
starting ChatList and finish home design and routes
adim806 Oct 17, 2024
61940de
add menu scroll on dashboard chats menu and design
adim806 Oct 18, 2024
3f2c6a1
Home screen design (chat menu and dashboard)
adim806 Oct 18, 2024
5d8ba8e
design the chat web (1:17) chat page jsx+css+add useRef HOOK
adim806 Oct 18, 2024
bb33823
BUILDING CSS 1 BY ONE (1:23)
adim806 Oct 18, 2024
20c5976
react secure image uploading
adim806 Oct 19, 2024
64de9d6
create a starter open api connected succes
adim806 Oct 19, 2024
23e52f6
added a open ai succ (1:56xx)
adim806 Oct 19, 2024
0db2ec2
some
adim806 Oct 19, 2024
d65055c
react chat image recognition
adim806 Oct 20, 2024
e5fe8d4
connected to mongoDB boy
adim806 Oct 20, 2024
96c05e9
monodb con
adim806 Oct 20, 2024
5173c6a
add a models for monoDB (2:18XX)
adim806 Oct 20, 2024
8298941
react mongoDB ADD A NEW CHAT
adim806 Oct 21, 2024
a308792
query part 1 - 2:46:30xx
adim806 Oct 21, 2024
06c8129
fetching data succes to menudashboard with react query
adim806 Oct 22, 2024
f4662e1
rotating data un query
adim806 Oct 22, 2024
fe6828e
finale
adim806 Oct 22, 2024
87ed33e
colors
adim806 Oct 22, 2024
7d62955
REACT AI , chat send a new message and save it to the DATABASE
adim806 Oct 27, 2024
a3f8ec3
succ DB in CHATS
adim806 Oct 27, 2024
3ed07be
added gitignore files
adim806 Oct 27, 2024
e684ba5
added docstrings
adim806 Oct 27, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ node_modules
dist
dist-ssr
*.local
.env

# Editor directories and files
.vscode/*
Expand All @@ -21,4 +22,4 @@ dist-ssr
*.ntvs*
*.njsproj
*.sln
*.sw?
*.sw?
3 changes: 0 additions & 3 deletions README.md

This file was deleted.

9 changes: 9 additions & 0 deletions backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
IMAGE_KIT_ENDPOINT=https://ik.imagekit.io/ula6wme9r
IMAGE_KIT_PUBLIC_KEY=public_FsV5vybnkOY0YhDMsT/8MTXGfDk=
IMAGE_KIT_PRIVATE_KEY=private_1Sxplsxl+jLklEdO6ZrBDiYDsfU=

CLIENT_URL=http://localhost:5173
MONGO=mongodb+srv://adim806:[email protected]/aichat?retryWrites=true&w=majority&appName=Cluster0

CLERK_PUBLISHABLE_KEY=pk_test_ZnVua3ktZ29iYmxlci0zMS5jbGVyay5hY2NvdW50cy5kZXYk
CLERK_SECRET_KEY=sk_test_Jdg1ofwlGhOCiOjYsGKNBarOBUXlP3aPD9zSCJe24T
26 changes: 26 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local
.env

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
154 changes: 154 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import express from "express";
import cors from "cors";
import ImageKit from "imagekit";
import mongoose from "mongoose";
import Chat from "./models/chat.js";
import UserChats from "./models/userChats.js";
import { ClerkExpressRequireAuth } from "@clerk/clerk-sdk-node";

const port = process.env.PORT || 3000; // Define server port
const app = express(); // Create Express application

// Enable CORS with credentials, restricting origins to CLIENT_URL environment variable
app.use(
cors({
origin: process.env.CLIENT_URL,
credentials: true,
})
);

app.use(express.json()); // Parse JSON request bodies

// Connect to MongoDB
const connect = async () => {
try {
await mongoose.connect(process.env.MONGO); // Connect to MongoDB using the MONGO environment variable
console.log("Connected to mongoDB!");
} catch (err) {
console.log(err); // Log connection errors
}
};

// Configure ImageKit for image handling and authentication
const imagekit = new ImageKit({
urlEndpoint: process.env.IMAGE_KIT_ENDPOINT, // ImageKit URL endpoint
publicKey: process.env.IMAGE_KIT_PUBLIC_KEY, // ImageKit public key
privateKey: process.env.IMAGE_KIT_PRIVATE_KEY, // ImageKit private key
});

// Endpoint to provide ImageKit authentication parameters
app.get("/api/upload", (req, res) => {
const result = imagekit.getAuthenticationParameters(); // Generate authentication parameters
res.send(result);
});

// Endpoint to create a new chat
app.post("/api/chats", ClerkExpressRequireAuth(), async (req, res) => {
const userId = req.auth.userId; // Get authenticated user ID
const { text } = req.body; // Get text from request body

try {
// Create a new chat document
const newChat = new Chat({
userId: userId,
history: [{ role: "user", parts: [{ text }] }],
});
const savedChat = await newChat.save(); // Save chat to database

// Check if the user already has chats stored
const userChats = await UserChats.find({ userId: userId });

if (!userChats.length) {
// If user has no existing chats, create a new UserChats document
const newUserChats = new UserChats({
userId: userId,
chats: [{ _id: savedChat._id, title: text.substring(0, 40) }],
});
await newUserChats.save();
} else {
// If user has existing chats, append the new chat to the chats array
await UserChats.updateOne(
{ userId: userId },
{
$push: {
chats: {
_id: savedChat._id,
title: text.substring(0, 40),
},
},
}
);
}
res.status(201).send(newChat._id); // Respond with new chat ID
} catch (error) {
console.error(error);
res.status(500).send("Error creating chats!"); // Send error response if chat creation fails
}
});

// Endpoint to get user’s chat list
app.get("/api/userchats", ClerkExpressRequireAuth(), async (req, res) => {
const userId = req.auth.userId; // Get authenticated user ID
try {
const userChats = await UserChats.find({ userId: userId }); // Retrieve user's chats
res.status(200).send(userChats[0].chats); // Send chat list in response
} catch (error) {
console.error(error);
res.status(500).send("Error fetching userchats"); // Error handling
}
});

// Endpoint to get chat history by chat ID
app.get("/api/chats/:id", ClerkExpressRequireAuth(), async (req, res) => {
const userId = req.auth.userId; // Get authenticated user ID
try {
const chat = await Chat.findOne({ _id: req.params.id, userId: userId }); // Find chat by ID
res.status(200).send(chat); // Send chat details in response
} catch (error) {
console.error(error);
res.status(500).send("Error fetching chat"); // Error handling
}
});

// Endpoint to update chat history with a new conversation
app.put("/api/chats/:id", ClerkExpressRequireAuth(), async (req, res) => {
const userId = req.auth.userId; // Get authenticated user ID
const { question, answer, img } = req.body; // Get conversation details from request body

// Prepare new conversation items based on question, answer, and optional image
const newItems = [
...(question
? [{ role: "user", parts: [{ text: question }], ...(img && { img }) }]
: []),
{ role: "model", parts: [{ text: answer }] },
];

try {
const updatedChat = await Chat.updateOne(
{ _id: req.params.id, userId }, // Update specific chat by ID and user
{
$push: {
history: {
$each: newItems, // Append new conversation items to chat history
},
},
}
);
res.status(200).send(updatedChat); // Send updated chat in response
} catch (err) {
console.log(err);
res.status(500).send("Error adding conversation!"); // Error handling
}
});

// Global error handler for unauthenticated access
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(401).send("Unauthenticated!");
});

// Start server and initiate MongoDB connection
app.listen(port, () => {
connect();
console.log("Server running on 3000");
});
34 changes: 34 additions & 0 deletions backend/models/chat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import mongoose from "mongoose";

const chatSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
},
history: [
{
role: {
type: String,
enum: ["user", "model"],
required: true,
},
parts: [
{
text: {
type: String,
required: true,
},
},
],
img: {
type: String,
required: false,
},
},
],
},
{ timestamps: true }
);

export default mongoose.models.chat || mongoose.model("chat", chatSchema);
30 changes: 30 additions & 0 deletions backend/models/userChats.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import mongoose from "mongoose";

const userChatsSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
},
chats: [
{
_id: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
},
],
},
{ timestamps: true }
);

export default mongoose.models.userchats ||
mongoose.model("userchats", userChatsSchema);
16 changes: 16 additions & 0 deletions backend/node_modules/.bin/loose-envify

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions backend/node_modules/.bin/loose-envify.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions backend/node_modules/.bin/loose-envify.ps1

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions backend/node_modules/.bin/nodemon

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions backend/node_modules/.bin/nodemon.cmd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading