import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db'; import {RouteRating} from './RouteRating.interface'; /** * Fetches and returns all ratings for the given route * @param route_id The id of the route to get the ratings for * @return Promise The ratings */ export const findByRoute = async (route_id: string): Promise => { let conn = ClimbingRouteRatingDB.getConnection(); try { return await conn.query('SELECT rating_id, route_id, stars, timestamp FROM route_ratings WHERE route_id = ?', route_id); } catch (err) { throw err; } }; /** * Get the median amount of stars the given route got from climbers * @param route_id The id of the route to get the rating for * @return number The median amount of stars with 1 fraction digit. */ export const getStarsForRoute = async (route_id: string): Promise => { let ratings = await findByRoute(route_id); let starsSum = 0; let starsAmount = 0; for (let rating of ratings) { starsSum += rating.stars; starsAmount++; } return Number((starsSum / starsAmount).toFixed(1)); }; /** * Creates a new rating and returns the id * @param route_id The id of the route to be rated * @param stars The amount of stars to be given * @return number The id of the created rating */ export const createRating = async (route_id: string, stars: number): Promise => { let conn = ClimbingRouteRatingDB.getConnection(); try { let res = await conn.query('INSERT INTO route_ratings (route_id, stars) VALUES (?, ?) RETURNING rating_id', [route_id, stars]); return res[0].comment_id; } catch (err) { throw err; } };