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

Rahul - Added HGN Form Backend Code #1164

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
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
Binary file modified .DS_Store
Binary file not shown.
92 changes: 46 additions & 46 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/hgn-form/backend/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
PORT=5000
MONGO_URI=<--add your url here-->
22 changes: 22 additions & 0 deletions src/hgn-form/backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# **HGN Form - Backend**

## **Getting Started**

Before starting, create an ".env" file in the 'backend' folder and add your MongoDB URL as MONGO_URI=<Your Mongo URL\> and set PORT=5000

1. Change directory:
```bash
cd backend
```
2. Install dependencies:
```bash
npm install
```
3. Seed the questions data into your MongoDB database:
```bash
node seed.js
```
4. Start the development server:
```bash
node server.js
```
9 changes: 9 additions & 0 deletions src/hgn-form/backend/models/Question.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require("mongoose");

const QuestionSchema = new mongoose.Schema({
text: { type: String, required: true },
page: { type: Number, required: true },
title: { type: String, required: true },
});

module.exports = mongoose.model("Question", QuestionSchema);
2,123 changes: 2,123 additions & 0 deletions src/hgn-form/backend/package-lock.json

Large diffs are not rendered by default.

25 changes: 25 additions & 0 deletions src/hgn-form/backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"mongodb": "^4.15.0",
"mongoose": "^6.10.0"
},
"devDependencies": {
"nodemon": "^3.1.7"
}
}
83 changes: 83 additions & 0 deletions src/hgn-form/backend/routes/questions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
const express = require("express");
const Question = require("../models/Question");

const router = express.Router();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Consider adding validation for POST and PUT here
const validateQuestion = (req, res, next) => {
const { text, page, title } = req.body;
if (!text?.trim() || !page || !title?.trim()) {
return res.status(400).json({ error: "Invalid question data" });
}
next();
};
// router.post("/", validateQuestion, async (req, res) => {
//. Existing POST route code here
//});
//router.put("/:id", validateQuestion, async (req, res) => {
// Existing PUT route here
//});

// GET all questions or filtered questions according to the pages and title
router.get("/", async (req, res) => {
try {
const { page, title } = req.query; // Retrieve query parameters
const query = {};

if (page) query.page = Number(page); // Add page filter if provided
if (title) query.title = title; // Add title filter if provided

const questions = await Question.find(query); // Fetch matching questions
res.json(questions);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
res.json(questions);
if (!questions.length) {
return res.status(404).json({ message: "No questions found" });
}
res.json(questions);

} catch (err) {
res.status(500).json({ error: err.message });
}
});

// POST a new question
router.post("/", async (req, res) => {
const { text, page, title } = req.body;

if (!text || !page || !title) {
return res
.status(400)
.json({ error: "All fields (text, page, title) are required" });
}

try {
const question = new Question({ text, page, title });
await question.save();
res.status(201).json(question);
} catch (err) {
res
.status(500)
.json({ error: "Failed to create question: " + err.message });
}
});

// PUT (update) an existing question by ID
router.put("/:id", async (req, res) => {
const { text, page, title } = req.body;

try {
const updatedQuestion = await Question.findByIdAndUpdate(
req.params.id,
{ text, page, title },
{ new: true }
);

if (!updatedQuestion) {
return res.status(404).json({ error: "Question not found" });
}

res.json(updatedQuestion);
} catch (err) {
res
.status(500)
.json({ error: "Failed to update question: " + err.message });
}
});

// DELETE an existing question by ID
router.delete("/:id", async (req, res) => {
try {
const deletedQuestion = await Question.findByIdAndDelete(req.params.id);

if (!deletedQuestion) {
return res.status(404).json({ error: "Question not found" });
}

res.json({ message: "Question deleted successfully" });
} catch (err) {
res
.status(500)
.json({ error: "Failed to delete question: " + err.message });
}
});

module.exports = router;
205 changes: 205 additions & 0 deletions src/hgn-form/backend/seed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
const mongoose = require("mongoose");
const Question = require("./models/Question");
require("dotenv").config();

const MONGO_URI = process.env.MONGO_URI;

const seedQuestions = async () => {
try {
await mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("Connected to MongoDB");

// Grouped questions by category
const pageQuestions = {
page1: [
{ title: "user_info", text: "Name" },
{ title: "user_info", text: "Email" },
{ title: "user_info", text: "GitHub" },
{ title: "user_info", text: "Slack" },
],
page2: [
{
title: "general",
text: "Which of the following best describes your weekly volunteer hours commitment with One Community?",
},
{
title: "general",
text: "How much longer do you anticipate volunteering with us?",
},
{
title: "general",
text: "Would you be interested in weekly (or biweekly) standup meetings to discuss coding and your progress?",
},
{
title: "general",
text: "Confirm your location for the foreseeable future so we can confirm the time zones for these meetings (Answer format: City, State, Country)",
},
{
title: "general",
text: "Are you interested in managing a team or doing any management work?",
},
{
title: "general",
text: "How would you rate your combined frontend/backend skills as a developer? (1-10, 10 being the highest)",
},
{
title: "general",
text: "How would you rate your combined skills as a developer? (1-10, 10 being the highest)",
},
{
title: "general",
text: "How would you score yourself on MERN (MongoDB, Express, React, Node) stack development? (1-10, 10 being the highest)",
},
{
title: "general",
text: "How would you rate your overall leadership/management/people SKILLS? (1-10, 10 being the highest)",
},
{
title: "general",
text: "How would you rate your overall leadership/management EXPERIENCE? (1-10, 10 being the highest)",
},
{
title: "general",
text: "Do you have any preference where you'd like to put your energy?",
},
{
title: "general",
text: "Confirm your availability in PACIFIC TIMEZONE (PT)",
},
],
page3: [
{
title: "frontend",
text: "How would you score yourself overall on the frontend (1-10, ten being the highest)? Including JavaScript, React.js, HTML/CSS, etc.",
},
{
title: "frontend",
text: "How would you score yourself on your understanding of HTML semantics and best practices (1-10, ten being the highest)?",
},
{
title: "frontend",
text: "How would you score yourself on your understanding of Bootstrap (1-10, ten being the highest)?",
},
{
title: "frontend",
text: "How would you score yourself on your understanding of advanced CSS techniques (1-10, ten being the highest)? (grid, flex box, clamp, media queries, transitions & animations, pseudo-classes & pseudo elements, advanced selectors, preprocessors, cross-browser compatibility, optimization, and performance)",
},
{
title: "frontend",
text: "How would you score yourself on your understanding and ability to utilize advanced features of React (1-10, ten being the highest)?",
},
{
title: "frontend",
text: "How would you score yourself on your understanding and ability to advanced features of Redux (1-10, ten being the highest)?",
},
{
title: "frontend",
text: "On a scale of 1-10, how comfortable are you integrating web socket communications in the front end?",
},
{
title: "frontend",
text: "How would you score yourself on responsive web design and UI development (1-10, ten being the highest)?",
},
{
title: "frontend",
text: "How would you score yourself on testing (1-10, ten being the highest)? Like Unit Testing with Jest or RTL.",
},
{
title: "frontend",
text: "How would you score yourself on documentation (1-10, ten being the highest)? Like writing Markdown files and drawing all kinds of graphs during design and development.",
},
{
title: "frontend",
text: "How would you score yourself on UX/UI design (1-10, ten being the highest)? With tools like Figma.",
},
],
page4: [
{
title: "backend",
text: "How would you score yourself on the backend (1-10, ten being the highest)? Including advanced JavaScript coding and debugging.",
},
{
title: "backend",
text: "How would you score yourself on database (1-10, ten being the highest)? Including advanced topics like aggregation, setup, etc.",
},
{
title: "backend",
text: "How would you score yourself on using MongoDB in relation to setup, advanced query calls, and handling of data (1-10, ten being the highest)?",
},
{
title: "backend",
text: "How would you score yourself on your ability to create a mock MongoDB database and integrate that into your backend testing in order to create a more robust backend (1-10, ten being the highest)?",
},
{
title: "backend",
text: "How would you score yourself on test driven development in the backend (1-10, ten being the highest)?",
},
{
title: "backend",
text: "How would you score yourself on deployment (1-10, ten being the highest)? With tools like Azure, Docker, Bluehost, CicleCI, surge CDN, etc.",
},
{
title: "backend",
text: "How would you score yourself on version control (1-10, ten being the highest)? Including advanced topics like rebase, patch, stash, cherry-picking, etc.",
},
{
title: "backend",
text: "How would you score yourself on advanced code review skills (1-10, ten being the highest)? Like finding the root causes of bugs and giving suggestions to improve the author’s code, either on functionalities or the codes performance.",
},
{
title: "backend",
text: "How would you score yourself on environment setup on Windows or Linux (Unix) (1-10, ten being the highest)? With knowledge in scripting language like Shell.",
},
{
title: "backend",
text: "How would you score yourself on advanced coding skills (1-10, ten being the highest)? Like software design, performance improvement, code cleaning-up, etc.",
},
{
title: "backend",
text: "How would you score yourself on Agile development (1-10, ten being the highest)? With tools like Jira, Bamboo, etc.",
},
],
page5: [
{
title: "followup",
text: "What platform are you using for developing? (Windows, macOS, Linux, etc)",
},
{
title: "followup",
text: "Do you have experience in any other technical skills we might use in future? Like data analysis, machine learning, etc.",
},
{
title: "followup",
text: "Is there anything else you think we've missed and/or that you suggest we should add here?",
},
{
title: "followup",
text: "Is there anything else you'd like to share with us?",
},
],
};

// Flatten questions and add page numbers
const questions = Object.entries(pageQuestions).flatMap(
([pageKey, questionsArray], index) =>
questionsArray.map((question) => ({ ...question, page: index + 1 }))
);

// Clear existing questions to prevent duplicates
await Question.deleteMany({});
console.log("Existing questions cleared.");

// Insert the new questions into the database
await Question.insertMany(questions);
console.log("Questions seeded successfully!");
process.exit(0);
} catch (err) {
console.error("Error seeding questions:", err);
process.exit(1);
}
};

seedQuestions();
32 changes: 32 additions & 0 deletions src/hgn-form/backend/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const bodyParser = require("body-parser");
const questionRoutes = require("./routes/questions");
require("dotenv").config();

const app = express();

const PORT = process.env.PORT || 5000;
const MONGO_URI = process.env.MONGO_URI;

// Middleware
const corsOptions = {
origin: "http://localhost:3000", // Allow frontend origin
methods: ["GET", "POST", "PUT", "DELETE"],
};

app.use(cors(corsOptions));
app.use(bodyParser.json());

// Routes
app.use("/api/questions", questionRoutes);

// Connect to MongoDB and start server
mongoose
.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("Connected to MongoDB");
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
})
.catch((err) => console.error("MongoDB connection error:", err));
5 changes: 5 additions & 0 deletions src/hgn-form/backend/setup.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# To populate questions data in database
node seed.js

# To start backend
node server.js
Loading