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

Feature/mraysu/add students backend #57

Closed
wants to merge 9 commits into from
Closed
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
6 changes: 6 additions & 0 deletions backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ void mongoose
console.log(error);
});

server.app.use(
cors({
origin: process.env.FRONTEND_ORIGIN,
}),
);

// Middleware
server.app.use(json());

Expand Down
3 changes: 0 additions & 3 deletions backend/src/controllers/student.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
/* eslint-disable @typescript-eslint/no-misused-promises */
/**
* Functions that process task route requests.
*/

import { RequestHandler } from "express";
import { validationResult } from "express-validator";
Expand Down
8 changes: 5 additions & 3 deletions backend/src/validators/student.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,12 @@ const makeProg1Validator = () =>
.exists()
.withMessage("Program 1 field required")
.bail()
.isString()
.withMessage("Program 1 must be a string");
.isArray()
.withMessage("Program 1 must be an array");

//prog2
const makeProg2Validator = () =>
body("prog2").optional().isString().withMessage("Program 2 must be a string");
body("prog2").optional().isArray().withMessage("Program 2 must be an array");

//dietary
//validates entire array
Expand Down Expand Up @@ -151,4 +151,6 @@ export const createStudent = [
makeDietaryArrayValidator(),
makeDietaryItemsValidator(),
makeDietaryOtherValidator(),
body("prog2.*").isString().withMessage("Programs must be strings"),
body("prog1.*").isString().withMessage("Programs must be strings"),
];
12 changes: 12 additions & 0 deletions frontend/package-lock.json

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

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"date-fns": "^3.2.0",
"dotenv": "^16.4.2",
"firebase": "^10.7.1",
"lucide-react": "^0.311.0",
"next": "14.0.4",
Expand Down
11 changes: 6 additions & 5 deletions frontend/src/api/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* Custom type definition for the HTTP methods handled by this module.
*/
type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;

/**
* Throws an error if the status code of the HTTP response indicates an error. If an HTTP error was
Expand Down Expand Up @@ -68,7 +69,7 @@ async function fetchRequest(
* @returns A `Response` object returned by `fetch()`
*/
export async function GET(url: string, headers: Record<string, string> = {}): Promise<Response> {
return await fetchRequest("GET", url, undefined, headers);
return await fetchRequest("GET", API_BASE_URL + url, undefined, headers);
}

/**
Expand All @@ -84,7 +85,7 @@ export async function POST(
body: unknown,
headers: Record<string, string> = {},
): Promise<Response> {
return await fetchRequest("POST", url, body, headers);
return await fetchRequest("POST", API_BASE_URL + url, body, headers);
}

/**
Expand All @@ -100,7 +101,7 @@ export async function PUT(
body: unknown,
headers: Record<string, string> = {},
): Promise<Response> {
return await fetchRequest("PUT", url, body, headers);
return await fetchRequest("PUT", API_BASE_URL + url, body, headers);
}

/**
Expand All @@ -116,7 +117,7 @@ export async function PATCH(
body: unknown,
headers: Record<string, string> = {},
): Promise<Response> {
return await fetchRequest("PATCH", url, body, headers);
return await fetchRequest("PATCH", API_BASE_URL + url, body, headers);
}

/**
Expand All @@ -132,7 +133,7 @@ export async function DELETE(
body: unknown,
headers: Record<string, string> = {},
): Promise<Response> {
return await fetchRequest("DELETE", url, body, headers);
return await fetchRequest("DELETE", API_BASE_URL + url, body, headers);
}

/**
Expand Down
64 changes: 64 additions & 0 deletions frontend/src/api/students.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { POST, handleAPIError } from "../api/requests";
import { Contact, StudentData } from "../components/StudentForm/types";

import type { APIResult } from "../api/requests";

export type Student = {
_id: string;
student: Contact;
emergency: Contact;
serviceCoordinator: Contact;
location: string;
medication?: string;
birthday: Date;
intakeDate: Date;
tourDate: Date;
regular_programs: string[];
varying_programs: string[];
dietary: string[];
otherString?: string;
};

type StudentJSON = {
_id: string;
student: Contact;
emergency: Contact;
serviceCoordinator: Contact;
location: string;
medication?: string;
birthday: string;
intakeDate: string;
tourDate: string;
regular_programs: string[];
varying_programs: string[];
dietary: string[];
otherString?: string;
};

function parseStudent(studentJSON: StudentJSON): Student {
return {
_id: studentJSON._id,
student: studentJSON.student,
emergency: studentJSON.emergency,
serviceCoordinator: studentJSON.serviceCoordinator,
location: studentJSON.location,
medication: studentJSON.medication,
birthday: new Date(studentJSON.birthday),
intakeDate: new Date(studentJSON.intakeDate),
tourDate: new Date(studentJSON.tourDate),
regular_programs: studentJSON.regular_programs,
varying_programs: studentJSON.varying_programs,
dietary: studentJSON.dietary,
otherString: studentJSON.otherString,
} as Student;
}

export async function createStudent(student: StudentData): Promise<APIResult<Student>> {
Copy link
Contributor

Choose a reason for hiding this comment

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

It may be good to add a check here to make sure that the contact information (email, phone) provided of the emergency contact is different from the contact information (email, phone) of the student

try {
const response = await POST("/api/student", student);
const json = (await response.json()) as StudentJSON;
return { success: true, data: parseStudent(json) };
} catch (error) {
return handleAPIError(error);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default function StudentBackground({
/>
</div>
<div>
<h3>Mediciation</h3>
<h3>Medication</h3>
<Textfield
register={register}
name="medication"
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/StudentForm/StudentInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type StudentInfoProps = {
data: StudentData | null;
};

// Temporary as long as we are storing programs as strings instead of ids
const regularPrograms = ["Intro", "ENTR"];
const varyingPrograms = ["TDS", "SDP"];

Expand Down Expand Up @@ -62,7 +63,7 @@ export default function StudentInfo({
<h3>Varying Programs</h3>
<Checkbox
register={register}
name="regular_programs"
name="varying_programs"
options={varyingPrograms}
defaultValue={data?.prog2}
/>
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/StudentForm/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ export type StudentFormData = {
intake_date: string;
tour_date: string;
regular_programs: string[];
varying_programs: string[];
};
31 changes: 25 additions & 6 deletions frontend/src/components/StudentFormButton.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";

import { createStudent } from "../api/students";
import { cn } from "../lib/utils";

import { Button } from "./Button";
Expand Down Expand Up @@ -55,15 +56,33 @@ export default function StudentFormButton({
},
location: formData.address,
medication: formData.medication,
birthday: formData.birthdate,
intakeDate: formData.intake_date,
tourDate: formData.tour_date,
prog1: formData.regular_programs,
prog2: formData.regular_programs,
// Syntax is to prevent runtime errors when attempting to make dates with invalid date strings
birthday: Date.parse(formData.birthdate) ? new Date(formData.birthdate).toISOString() : "",
intakeDate: Date.parse(formData.intake_date)
? new Date(formData.intake_date).toISOString()
: "",
tourDate: Date.parse(formData.tour_date) ? new Date(formData.tour_date).toISOString() : "",
prog1: formData.regular_programs ? formData.regular_programs : ([] as string[]),
prog2: formData.varying_programs ? formData.varying_programs : ([] as string[]),
dietary: formData.dietary,
otherString: formData.other,
};
reset(); //Clear form
if (type === "add") {
createStudent(transformedData).then(
(result) => {
if (result.success) {
reset(); // only clear form on success
} else {
console.log(result.error);
alert("Unable to create student: " + result.error);
}
},
(error) => {
console.log(error);
},
);
}
//uncomment for testing
console.log(`${type} student data:`, transformedData);
};

Expand Down
8 changes: 6 additions & 2 deletions frontend/src/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import CreateUser from "./create_user";
import StudentFormButton from "../components/StudentFormButton";

export default function Home() {
return <CreateUser />;
return (
<div className="grid w-40 gap-5">
<StudentFormButton type="add" />
</div>
);
}
Loading