69 lines
2.0 KiB
TypeScript
69 lines
2.0 KiB
TypeScript
import {ClimbingRouteRatingDB} from '../ClimbingRouteRating.db';
|
|
import {ClimbingRoute} from './ClimbingRoute.interface';
|
|
import random from 'random-words';
|
|
|
|
/**
|
|
* Fetches and returns all known climbing routes
|
|
* @return Promise<ClimbingRoute[]> The climbing routes
|
|
*/
|
|
export const findAll = async (): Promise<ClimbingRoute[]> => {
|
|
let conn = await ClimbingRouteRatingDB.getConnection();
|
|
try {
|
|
return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes');
|
|
} catch (err) {
|
|
throw err;
|
|
} finally {
|
|
// Return connection
|
|
await conn.end();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Fetches and returns information about the given route
|
|
* @param route_id The id of the route
|
|
* @return Promise<ClimbingRoute> The climbing route
|
|
*/
|
|
export const findById = async (route_id: string): Promise<ClimbingRoute> => {
|
|
let conn = await ClimbingRouteRatingDB.getConnection();
|
|
try {
|
|
return await conn.query('SELECT route_id, gym_id, name, difficulty, route_setting_date FROM climbing_routes WHERE route_id = ?', route_id);
|
|
} catch (err) {
|
|
throw err;
|
|
} finally {
|
|
// Return connection
|
|
await conn.end();
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Creates a new route and returns the id of the created route
|
|
* @param gym_id The id of the climbing gym that the route belongs to
|
|
* @param name The name of the climbing route
|
|
* @param difficulty The difficulty of the climbing route
|
|
* @return string The id of the created route
|
|
*/
|
|
export const createRoute = async (gym_id: number, name: string, difficulty: string): Promise<string> => {
|
|
let conn = await ClimbingRouteRatingDB.getConnection();
|
|
|
|
// Generate route id
|
|
let route_id = '';
|
|
let randWords = random(3);
|
|
for (let i = 0; i <= 2; i++) {
|
|
route_id += randWords[i];
|
|
if (i < 2) {
|
|
route_id += '-';
|
|
}
|
|
}
|
|
|
|
try {
|
|
await conn.query('INSERT INTO climbing_routes (route_id, gym_id, name, difficulty) VALUES (?, ?, ?, ?)', [route_id, gym_id, name, difficulty]);
|
|
|
|
return route_id;
|
|
} catch (err) {
|
|
throw err;
|
|
} finally {
|
|
// Return connection
|
|
await conn.end();
|
|
}
|
|
};
|