Skip to content

Commit

Permalink
509 feature fetch rating of a room from database (#548)
Browse files Browse the repository at this point in the history
* added insert function

* changed to roomid

* changed require to import and added .env

* added get end point for room ratings

* chore(deps): lock file maintenance (#534)

* chore(deps): lock file maintenance

* chore(deps): lock file maintenance

* Update node-version in ci.yml

* chore(deps): lock file maintenance

* chore(deps): lock file maintenance

* Fix frontend npm install

* Fix missing frontend test dependencies

* Add typescript es2018 for common folder

* Update target to ES2018

* Change backend tsconfig target

* chore(deps): lock file maintenance

* Updated package-lock

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Jessica Feng <[email protected]>
Co-authored-by: Jessica <[email protected]>

* chore(deps): update weekly minor & patch updates (#535)

* chore(deps): update weekly minor & patch updates

* Try resolve app dependencies

* chore(deps): update weekly minor & patch updates

* Performed npm install

* Perform npm install

* Remove unnecessary appDir config

* Update layout.tsx

* Update TSConfig target and lib

* Attempt to resolve build issues

* chore(deps): update weekly minor & patch updates

* chore(deps): update weekly minor & patch updates

* Fix npm packages

* Remove unnecessary files

* Update frontend typescript target

* chore(deps): update weekly minor & patch updates

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Jessica <[email protected]>
Co-authored-by: Jessica Feng <[email protected]>

* fix(deps): update material-ui monorepo to v6 (major) (#532)

* fix(deps): update dependency @mui/x-date-pickers to v7

* Fixed and upgraded MUI date picker

* Fixed BuildingDrawer date picker

* fix(deps): update material-ui monorepo to v6

* Updated frontend package-lock

* Fix BuildingDrawer

* Add path-scurry

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Jessica Feng <[email protected]>
Co-authored-by: Jessica <[email protected]>

* 498 circular display rating (#525)

* initial planning

* initial planning

* finished circular rating

* fixed linting

* added testing

* fixed linting

* changed the border so that it reflects the rating

* fixed linting

* moved circular rating into its own file

* created additional files for CircularRating component

* removed unused imports

---------

Co-authored-by: Sophia Liu <[email protected]>
Co-authored-by: Jessica Feng <[email protected]>

* modified getRatings return type

* created useRoomRatings hook

* fixed useRoomRatings api path

* display average room ratings

* added roomID prop to BookingCalendar

* added error checking for ratings array

* refactored average room rating calculation

* fixed linting

* removed console logs

* added patches to getRatings

* formatted rating get route to use asyncHandler

* modified insertRating logic

* modified getRatings logic

* updated insertRating and getRatings parameters to match FE

* updated useRoomRatings hook to use new return type

* added userInsertRating hook

* added location and overall circular ratings

---------

Co-authored-by: cherisechan <[email protected]>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Jessica Feng <[email protected]>
Co-authored-by: Jessica <[email protected]>
Co-authored-by: Sophia Liu <[email protected]>
Co-authored-by: Sophia Liu <[email protected]>
  • Loading branch information
7 people authored Oct 8, 2024
1 parent 6b1577a commit 8008609
Show file tree
Hide file tree
Showing 13 changed files with 358 additions and 21 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ typings/
# dotenv environment variables file
.env
.env.test
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
Expand Down
143 changes: 141 additions & 2 deletions backend/package-lock.json

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

4 changes: 3 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@
"cors": "^2.8.5",
"date-fns": "^2.30.0",
"date-fns-tz": "^2.0.0",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"graphql": "^16.6.0",
"graphql-request": "^6.1.0"
"graphql-request": "^6.1.0",
"mongodb": "^6.8.0"
},
"devDependencies": {
"@types/cors": "2.8.17",
Expand Down
26 changes: 26 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import cors from "cors";
import express, {
json,
NextFunction,
Request,
RequestHandler,
Response,
} from "express";

import { PORT } from "./config";
import { getRatings, insertRating } from "./ratingDbInterface";
import {
parseSearchFilters,
parseStatusDatetime,
Expand All @@ -22,6 +24,7 @@ import {

const app = express();
app.use(cors());
app.use(json());

// Wrapper for request handler functions to catch async exceptions
const asyncHandler =
Expand Down Expand Up @@ -83,6 +86,29 @@ app.get(
})
);

// get all ratings for a room given roomId
app.get(
"/api/rating/:roomID",
asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
const { roomID } = req.params;
const roomRatings = await getRatings(roomID);
res.send(roomRatings);
next();
})
);

// insert one rating
app.post("/api/rating/rate", async (req: Request, res: Response) => {
const { roomId, quietness, location, cleanliness, overall } = req.body;
const ratings = [quietness, location, cleanliness, overall];
try {
await insertRating(roomId, ratings);
res.status(200).json({ message: "rating inserted successfully" });
} catch (error) {
res.status(500).json({ error: error });
}
});

// Error-handling middleware
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
console.error(`"${req.originalUrl}" ${err.stack ?? err}`);
Expand Down
80 changes: 80 additions & 0 deletions backend/src/ratingDbInterface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Rating, RatingsResponse } from "@common/types";
import dotenv from "dotenv";
import { Collection, MongoClient } from "mongodb";
dotenv.config({ path: "src/.env.local" });

const uri: string | undefined = process.env.MONGODB_URI;

export async function insertRating(
roomId: string,
ratings: number[]
): Promise<void> {
if (!uri) {
throw new Error("uri not found");
}

const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db("room-ratings");
const collection: Collection<RatingsResponse> =
database.collection("ratings");

const ratingObject: Rating = {
quitness: ratings[0],
location: ratings[1],
cleanliness: ratings[2],
overall: ratings[3],
};

// Update this room's document with new ratings
// If no documents exist for the current room, create one with ratings array
const filter = { roomId: roomId };
const options = {
upsert: true,
};
await collection.updateOne(
filter,
{ $push: { ratings: ratingObject } },
options
);
} catch (error) {
console.error("Error inserting document:", error);
} finally {
await client.close();
}
}

export async function getRatings(roomId: string): Promise<Rating[]> {
if (!uri) {
throw new Error("uri not found");
}

const client = new MongoClient(uri);

try {
await client.connect();
const database = client.db("room-ratings");
const collection = database.collection("ratings");
const query = { roomId: roomId };

// Include only 'roomId' and 'ratings' fields in each document
const options = {
projection: { _id: 0, roomId: 1, ratings: 1 },
};

const roomDoc = await collection.findOne(query, options);

// Document found, return ratings array
if (roomDoc !== null) {
const roomRating = roomDoc as unknown as RatingsResponse;
return roomRating.ratings;
}
} catch (error) {
console.error("Error finding item:", error);
} finally {
await client.close();
}
// No document found, return empty array
return [];
}
13 changes: 13 additions & 0 deletions common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ export type School = {
contactLink: string;
};

export type Rating = {
quitness: number;
location: number;
cleanliness: number;
overall: number;
}

///////////////////////////////////////////////////////////////
// API Response Types

Expand All @@ -68,3 +75,9 @@ export type SearchResponse = {
export type BookingsResponse = {
bookings: Booking[];
};

export type RatingsResponse = {
// roomId refers to room name
roomId: string;
ratings: Rating[];
}
Loading

0 comments on commit 8008609

Please sign in to comment.