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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
51 changes: 51 additions & 0 deletions backend/importSearchResults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const fs = require('fs');
const path = require('path');
const { MongoClient } = require('mongodb');

// MongoDB connection URI
const uri = "mongodb+srv://root:root@cluster0.cnbie.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
const client = new MongoClient(uri);

const dataDir = './F25SearchResults'; // Adjust this if your files are in a subfolder

async function importData() {
try {
await client.connect();
const db = client.db('classes');
const collection = db.collection('course');

// Optional: Clear existing data
await collection.deleteMany({});

let totalInserted = 0;

for (let i = 1; i <= 22; i++) {
const filename = `searchResults${String(i).padStart(2, '0')}.json`; // Ensures 01–22 format
const filepath = path.join(dataDir, filename);

if (fs.existsSync(filepath)) {
const fileContent = fs.readFileSync(filepath, 'utf-8');
const jsonData = JSON.parse(fileContent);

if (jsonData && Array.isArray(jsonData.data)) {
const cleanData = jsonData.data.filter(c => c.courseTitle && c.subject);
const result = await collection.insertMany(cleanData);
totalInserted += result.insertedCount;
console.log(`✔ Inserted ${result.insertedCount} records from ${filename}`);
} else {
console.warn(`⚠ No valid data in ${filename}`);
}
} else {
console.warn(`⚠ File not found: ${filename}`);
}
}

console.log(`✅ Import complete. Total documents inserted: ${totalInserted}`);
} catch (error) {
console.error("❌ Import failed:", error);
} finally {
await client.close();
}
}

importData();
55 changes: 55 additions & 0 deletions backend/routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// backend/routes.js
const express = require('express');
const router = express.Router();
const { MongoClient } = require('mongodb');

// MongoDB connection string
const uri = "mongodb+srv://root:root@cluster0.cnbie.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
let db = null;

// Connect to MongoDB once
async function connectDB() {
if (db) return db;
const client = new MongoClient(uri);
await client.connect();
db = client.db("classes");
return db;
}

// API endpoint to get all courses
router.get('/courses', async (req, res) => {
try {
const database = await connectDB();
const collection = database.collection("course");
const courses = await collection.find({}).toArray();
res.json(courses);
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Failed to fetch courses' });
}
});

// API endpoint to get a specific course
router.get('/courses/:subject/:courseNumber', async (req, res) => {
try {
const { subject, courseNumber } = req.params;
const database = await connectDB();
const collection = database.collection("course");

const course = await collection.findOne({
subject: subject,
courseNumber: courseNumber
});

if (!course) {
return res.status(404).json({ error: 'Course not found' });
}

res.json(course);
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'Failed to fetch course' });
}
});

module.exports = router;
41 changes: 40 additions & 1 deletion backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ const cors = require('cors');
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://root:root@cluster0.cnbie.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";


// Set up express app
const app = express();
app.use(cors());


// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
Expand All @@ -16,17 +18,20 @@ const client = new MongoClient(uri, {
}
});


async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Send a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");


const db = client.db('classes');
const collection = db.collection('course');


// Get entries from the database
app.get('/entries', async (req, res) => {
try {
Expand All @@ -37,15 +42,49 @@ async function run() {
}
});


//added this portion
// Modified endpoint to return multiple matches
app.get('/api/classes', async (req, res) => {
const query = req.query.name?.toLowerCase();
if (!query) return res.status(400).json({ error: "Missing search query" });


try {
const db = client.db('classes');
const collection = db.collection('course');


// Find multiple matches (limit to 10)
const results = await collection.find({
$or: [
{ courseTitle: { $regex: query, $options: "i" } },
{ courseNumber: { $regex: query, $options: "i" } },
{ subject: { $regex: query, $options: "i" } },
{ subjectCourse: { $regex: query, $options: "i" } }
]
}).limit(10).toArray();


res.json(results.length > 0 ? { success: true, data: results } : { success: false });
} catch (error) {
console.error("Error searching classes:", error);
res.status(500).json({ success: false, error: "Search failed" });
}
});


} catch (error) {
console.error("An error occurred while connecting to MongoDB:", error);
}
// Closing the client will close the connection before any requests are handled
}


const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});


run().catch(console.dir);
Binary file added frontend/public/Profile2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading