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

School crud #162

Merged
merged 4 commits into from
Apr 12, 2024
Merged
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
12 changes: 7 additions & 5 deletions client/src/components/SchoolQuerySearch.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ export const SchoolQuerySearch = ({ value, handleSearch }) => {

const fetchSchool = async (id) => {
try {
const data = await fetchWithAuth({
url: `${HOST}/api/school/get/${id}`,
method: 'GET',
})
data ? setQuery(data.name) : setQuery('')
if (id) {
const data = await fetchWithAuth({
url: `${HOST}/api/school/get/${id}`,
method: 'GET',
})
data ? setQuery(data.name) : setQuery('')
}
} catch (err) {
console.error('Error: ', err)
}
Expand Down
19 changes: 18 additions & 1 deletion client/src/pages/EditProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,16 @@ function EditProfile() {
setPipeline(temp)
}

const generateSchoolData = (pipeline) => {
const companyIDs = pipeline.map((company) => company.companyId)
// Set new school data
const newSchool = {
schoolId: school,
schoolTally: companyIDs,
}
return newSchool
}

const removeExperience = async (experience, index) => {
const newPipeline = [...pipeline]
const removeDate = [...dateValidity]
Expand Down Expand Up @@ -309,10 +319,10 @@ function EditProfile() {
setLoading(true)
sortByDate(pipeline)
generateCompanies(pipeline)
const schoolsData = generateSchoolData(pipeline)

// Update companies
try {
console.log('profile: ', profile)
// Update user profile
await fetchWithAuth({
url: `${HOST}/api/profile/${user.profileId}`,
Expand All @@ -327,6 +337,13 @@ function EditProfile() {
data: [companies, origCompanies, [school, origSchool]],
})

// update schools associated with user profile change
await fetchWithAuth({
url: `${HOST}/api/school/update/${school}`,
method: 'PATCH',
data: [schoolsData, origSchool],
})

dispatch({ type: 'CREATED', payload: user })
} catch (error) {
console.error('Error:', error.message)
Expand Down
2 changes: 0 additions & 2 deletions server/controllers/companyController.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,6 @@ const updateCompanies = async (req, res) => {
const origCompanies = companyArray[1]; // Old Pipeline
const newSchool = companyArray[2][0];
const oldSchool = companyArray[2][1];
console.log("New School: ", newSchool);
console.log("Old School: ", oldSchool);

const user = await Profile.findById(companies[0].userId);
if (!user) return res.status(404).json({ message: "User not found" });
Expand Down
93 changes: 93 additions & 0 deletions server/controllers/schoolController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,40 @@
const fetch = require("node-fetch");
const School = require("../models/schoolModel");

const createSchool = async (req, res) => {
if (!req.body.name) {
return res.status(400).json({ error: "No company name given." });
}

try {
const {
name,
domains,
state_province,
country,
alpha_two_code,
web_pages,
} = req.body; //pull school values from the request body

const newSchool = new School({
name: name,
domains: domains,
state_province: state_province,
country: country,
alpha_two_code: alpha_two_code,
web_pages: web_pages,
companyTally: {},
}); // Create New School object

const savedSchool = await newSchool.save();
console.log("New School Created: ", savedSchool.name);
console.log(savedSchool);
} catch (err) {
console.error(err);
res.status(500).json();
}
};

const searchSchools = async (req, res) => {
const { query } = req.params;

Expand Down Expand Up @@ -28,7 +62,66 @@ const getSchool = async (req, res) => {
}
};

const updateSchool = async (req, res) => {
const { id } = req.params;
const schoolArray = req.body;
const newSchool = schoolArray[0];
const oldSchool = schoolArray[1];
try {
const newUpdateData = {
$inc: {},
};

const oldUpdateData = {
$inc: {},
};

//update school tally
if (id !== oldSchool) {
//up
for (let i = 0; i < newSchool.schoolTally.length; i++) {
newUpdateData.$inc[`schoolTally.${newSchool.schoolTally[i]}`] = 1;
oldUpdateData.$inc[`schoolTally.${newSchool.schoolTally[i]}`] = -1;
}
}
//update new school
const newResponse = await School.updateOne({ _id: id }, newUpdateData);
if (!newResponse) res.status(404).json({ message: "School not found" });

//update old school
const oldResponse = await School.updateOne(
{ _id: oldSchool },
oldUpdateData
);
if (!oldResponse) res.status(404).json({ message: "School not found" });
console.log(`School updated ${newSchool.schoolId}`);
res.status(200).json({ message: "School updated" });
} catch (err) {
console.error(err);
return res.status(500).json({ error: "Failed to retrieve school" });
}
};

const deleteSchool = async (req, res) => {
const { id } = req.params;
const result = await School.findOneAndDelete({
_id: id,
});

if (!result) {
return res.status(404).json({ error: "No such school." });
}

console.log("School Deleted: ", id);
console.log(result);

res.status(200).json(result);
};

module.exports = {
searchSchools,
getSchool,
updateSchool,
deleteSchool,
createSchool,
};
16 changes: 15 additions & 1 deletion server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,21 @@ const routes = [
middleware: [verifyToken, verifyProfile],
handler: profileRoutes.write,
},
{ path: "/api/school", middleware: [verifyToken], handler: schoolRoutes },
{
path: "/api/school/create",
middleware: [verifyToken, verifyAdmin],
handler: schoolRoutes.write,
},
{
path: "/api/school/delete/:id",
middleware: [verifyToken, verifyAdmin],
handler: schoolRoutes.write,
},
{
path: "/api/school",
middleware: [verifyToken],
handler: schoolRoutes.read,
},
{
path: "/api/company",
middleware: [verifyToken],
Expand Down
26 changes: 21 additions & 5 deletions server/routes/school.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
const express = require("express");
const { searchSchools, getSchool } = require("../controllers/schoolController");
const {
searchSchools,
getSchool,
updateSchool,
createSchool,
deleteSchool,
} = require("../controllers/schoolController");

const router = express.Router();
const read = express.Router();
const write = express.Router();

write.post("/create", createSchool);

// GET schools by query
router.get("/get/schools/:query", searchSchools);
read.get("/get/schools/:query", searchSchools);

read.patch("/update/:id", updateSchool);

read.get("/get/:id", getSchool);

router.get("/get/:id", getSchool);
write.get("/delete/:id", deleteSchool);

module.exports = router;
module.exports = {
read,
write,
};