Skip to content
Snippets Groups Projects
Commit 8792dcfc authored by Federico Hurtado's avatar Federico Hurtado
Browse files

Beginning of adding people

parent 9c6bcef5
No related branches found
No related tags found
No related merge requests found
...@@ -61,6 +61,7 @@ CREATE TABLE IF NOT EXISTS people ( ...@@ -61,6 +61,7 @@ CREATE TABLE IF NOT EXISTS people (
firstName VARCHAR(255) NOT NULL, firstName VARCHAR(255) NOT NULL,
lastName VARCHAR(255) NOT NULL, lastName VARCHAR(255) NOT NULL,
middleName VARCHAR(255), middleName VARCHAR(255),
maidenName VARCHAR(255),
suffix VARCHAR(32), suffix VARCHAR(32),
nickName VARCHAR(255), nickName VARCHAR(255),
techAlumniChapter INT, techAlumniChapter INT,
...@@ -73,8 +74,9 @@ CREATE TABLE IF NOT EXISTS people ( ...@@ -73,8 +74,9 @@ CREATE TABLE IF NOT EXISTS people (
CREATE TABLE IF NOT EXISTS peopleDegree ( CREATE TABLE IF NOT EXISTS peopleDegree (
peopleDegreeId INT PRIMARY KEY AUTO_INCREMENT, peopleDegreeId INT PRIMARY KEY AUTO_INCREMENT,
peopleId INT, peopleId INT,
degreeSubject VARCHAR(255),
degreeTypeId INT, degreeTypeId INT,
degreeDepartment VARCHAR(50),
degreeCollege VARCHAR(50),
degreeYear VARCHAR(16), degreeYear VARCHAR(16),
degreeDescription VARCHAR(255), degreeDescription VARCHAR(255),
FOREIGN KEY (peopleId) REFERENCES people(peopleId), FOREIGN KEY (peopleId) REFERENCES people(peopleId),
...@@ -116,3 +118,12 @@ CREATE TABLE IF NOT EXISTS peopleXInvolvement ( ...@@ -116,3 +118,12 @@ CREATE TABLE IF NOT EXISTS peopleXInvolvement (
FOREIGN KEY (peopleId) REFERENCES people(peopleId), FOREIGN KEY (peopleId) REFERENCES people(peopleId),
FOREIGN KEY (involvementId) REFERENCES involvementLookup(involvementId) FOREIGN KEY (involvementId) REFERENCES involvementLookup(involvementId)
); );
INSERT INTO stateLookup (stateId, name)
VALUES (1, 'Virginia');
INSERT INTO countryLookup (countryId, name)
VALUES (1, 'United States');
-- I think there is already a people table that exists in our DB and
-- has data that does not include peopoleID
\ No newline at end of file
const { pool } = require("../config/database/database.config");
async function addAddress(address, peopleId) {
// get all the parts of the address
let { address1, address2, city, state, country, zipCode, preferredAddress } =
address;
console.log("adding address...");
try {
// Use helper functions to look up stateId and countryId
const stateId = await _lookupStateId(state);
const countryId = await _lookupCountryId(country);
// query for adding the address
const query = `
INSERT INTO address (address1, address2, city, stateId, countryId, zipCode)
VALUES (?,?,?,?,?,?)
`;
// insert data into the address table
const [addressResult] = await pool.query(query, [
address1,
address2,
city,
stateId,
countryId,
zipCode,
]);
// get the id of the newly created address in the DB
const addressId = addressResult.insertId;
console.log(
"successfully inserted addressID " +
addressId +
" for person: " +
peopleId
);
// Now insert into the peopleXAddress table
const peopleAddressQuery = `
INSERT INTO peopleXAddress (peopleId, addressId, preferredAddress)
VALUES (?, ?, ?)
`;
const [peopleAddressResult] = await pool.query(peopleAddressQuery, [
peopleId,
addressId,
preferredAddress,
]);
console.log("Added into peopleXaddress");
return peopleAddressResult;
} catch (error) {
console.error(error);
}
}
// Private helper function to look up the stateId
async function _lookupStateId(state) {
// for now return 1 while tables are not populated
return 1;
// try {
// const lookupQuery = `
// SELECT stateId FROM stateLookup WHERE name = ?
// `;
// const [lookupResults] = await pool.query(lookupQuery, [state]);
// if (lookupResults.length === 0) {
// console.log("State not found");
// return null;
// }
// return lookupResults[0].stateId;
// } catch (error) {
// console.error(`Error looking up state: ${state}`, error);
// throw error;
// }
}
// Private helper function to look up the countryId
async function _lookupCountryId(country) {
// for now return 1 while tables are not populated
return 1;
// try {
// const lookupQuery = `
// SELECT countryId FROM countryLookup WHERE name = ?
// `;
// const [lookupResults] = await pool.query(lookupQuery, [country]);
// if (lookupResults.length === 0) {
// console.log("Country not found");
// return null;
// }
// return lookupResults[0].countryId;
// } catch (error) {
// console.error(`Error looking up country: ${country}`, error);
// throw error;
// }
}
module.exports = { addAddress };
const { pool } = require("../config/database/database.config");
async function addDegree(degree, peopleId) {
// get all the parts of the degree
let {
degreeType,
degreeDepartment,
degreeCollege,
degreeYear,
degreeDescription,
} = degree;
console.log("adding degree...");
try {
// Use the helper function to determine the degreeTypeId
degreeTypeId = await _lookupDegreeTypeId(degreeType);
const query = `
INSERT INTO peopleDegree (peopleId, degreeTypeId, degreeDepartment, degreeCollege, degreeYear, degreeDescription)
VALUES (?,?,?,?,?,?)
`;
// insert data into db
const [results] = await pool.query(query, [
peopleId,
degreeTypeId,
degreeDepartment,
degreeCollege,
degreeYear,
degreeDescription,
]);
return results;
} catch (error) {
console.error(error);
}
}
// Private helper function to look up the degreeTypeId
async function _lookupDegreeTypeId(degreeType) {
try {
// return null for now
return null;
// const lookupQuery = `
// SELECT degreeTypeId FROM degreeTypeLookup WHERE degreeType = ?
// `;
// const [lookupResults] = await pool.query(lookupQuery, [degreeType]);
// if (lookupResults.length === 0) {
// console.log("Degree type not found");
// return null;
// // throw new Error(`Invalid degree type: ${degreeType}`);
// }
// return lookupResults[0].degreeTypeId;
} catch (error) {
console.error(`Error looking up degree type: ${degreeType}`, error);
throw error;
}
}
module.exports = { addDegree };
const { pool } = require("../config/database/database.config");
async function addPerson(person) {
// extract all the values from person
let {
firstName,
lastName,
middleName,
maidenName,
suffix,
nickName,
techAlumniChapter,
classYear,
gradYear,
gradSemester,
gender,
} = person;
// find the integer that represents the alumni chapter (for now do 2)
techAlumniChapter = 2;
console.log("In here now");
try {
console.log("Adding person: ", firstName);
const query = `
INSERT INTO people (firstName, lastName, middleName, maidenName, suffix, nickName, techAlumniChapter, classYear, gradYear, gradSemester, gender)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`;
const [results] = await pool.query(query, [
firstName,
lastName,
middleName,
maidenName,
suffix,
nickName,
techAlumniChapter,
classYear,
gradYear,
gradSemester,
gender,
]);
// return the new person's id
return results.insertId;
} catch (error) {
console.error(error);
}
}
module.exports = { addPerson };
const { check, body, validationResult } = require("express-validator"); const { check, body, validationResult } = require("express-validator");
const express = require("express"); const express = require("express");
const peopleRouter = express.Router(); const peopleRouter = express.Router();
const { createPerson } = require("../service/peopleService");
/* /*
Function to check that the POST request body in Function to check that the POST request body in
create person contains the correct data types create person contains the correct data types
...@@ -41,18 +41,15 @@ const validateCreatePerson = [ ...@@ -41,18 +41,15 @@ const validateCreatePerson = [
.isIn(["male", "female", "other"]) .isIn(["male", "female", "other"])
.withMessage("Invalid gender"), .withMessage("Invalid gender"),
check("personInfo.maidenName")
.optional()
.isString()
.withMessage("Maiden name should be a string"),
// Validate degrees array // Validate degrees array
body("degrees").isArray().withMessage("Degrees should be an array"), body("degrees").isArray().withMessage("Degrees should be an array"),
body("degrees.*.subject") body("degrees.*.degreeType").isString().withMessage("Invalid degree type"),
.notEmpty()
.withMessage("Degree subject is required")
.isString()
.withMessage("Degree subject must be a string"),
body("degrees.*.degreeType")
.isIn(["AS", "BS", "MS", "PhD"])
.withMessage("Invalid degree type"),
body("degrees.*.degreeYear") body("degrees.*.degreeYear")
.notEmpty() .notEmpty()
...@@ -112,7 +109,7 @@ const validateCreatePerson = [ ...@@ -112,7 +109,7 @@ const validateCreatePerson = [
.withMessage("Each involvement must be a string"), .withMessage("Each involvement must be a string"),
]; ];
peopleRouter.post("/create", validateCreatePerson, (req, res) => { peopleRouter.post("/create", validateCreatePerson, async (req, res) => {
// ensure the request body has the correct data types // ensure the request body has the correct data types
const errors = validationResult(req); const errors = validationResult(req);
...@@ -121,6 +118,15 @@ peopleRouter.post("/create", validateCreatePerson, (req, res) => { ...@@ -121,6 +118,15 @@ peopleRouter.post("/create", validateCreatePerson, (req, res) => {
return res.status(400).json({ errors: errors.array() }); return res.status(400).json({ errors: errors.array() });
} }
try {
const person = await createPerson(req.body);
console.log("In people routes after add: ", person);
return res.status(201).json({ message: "person added successfully" });
} catch (error) {
console.log("error");
return res.status(500).json({ message: error });
}
// no logic for now, return 200 // no logic for now, return 200
return res.status(200).json({ message: "No errors" }); return res.status(200).json({ message: "No errors" });
}); });
......
const { addAddress } = require("../repository/addressRepository");
const { addDegree } = require("../repository/degreeRepository");
const { addPerson } = require("../repository/peopleRepository");
async function createPerson(person) {
// extract the parts of a person
const { personInfo, degrees, addresses, contacts, involvements } = person;
console.log("Adding person....");
// insert the personInfo into people table
const newPersonID = await addPerson(personInfo);
console.log("Added person ID: ", newPersonID);
// insert the degree information into the database
for (const degree of degrees) {
const addedDegree = await addDegree(degree, newPersonID);
console.log("added degree: ", degree);
}
// insert the address information into the database
for (const address of addresses) {
const addedAddress = await addAddress(address, newPersonID);
console.log("added address: ", address);
}
// insert the contact information into the database
for (const contact of contacts) {
}
// insert the involvment information into the database
for (const involvment of involvements) {
}
return newPersonID;
}
module.exports = { createPerson };
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment