plutoapi-v2/src/models/climbing-route-rating/route_ratings/routeRatings.service.ts

59 lines
1.7 KiB
TypeScript

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<RouteRating[]> The ratings
*/
export const findByRoute = async (route_id: string): Promise<RouteRating[]> => {
let conn = await 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;
} finally {
// Return connection
await conn.end();
}
};
/**
* 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<number> => {
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<number> => {
let conn = await 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;
} finally {
// Return connection
await conn.end();
}
};