snowva-backend / src /controllers /adventureController.ts
zerito's picture
Deploy backend update Fri Dec 5 11:40:50 CET 2025
76816cb
Raw
History Blame Contribute Delete
6.93 kB
import { Request, Response } from 'express';
import { AdventureModel } from '../models/AdventureModel';
import { AdventureFeature, AdventureFeatureCollection } from '../types/types';
/**
* AdventureController - Handles HTTP requests for user-saved adventures
*/
export class AdventureController {
/**
* GET /api/adventures
* Fetch all adventures, optionally filtered by user_id
*/
static async getAdventures(req: Request, res: Response): Promise<void> {
console.log('--- Start getAdventures Controller ---');
try {
const { user_id } = req.query;
console.log(`Received query parameters: user_id=${user_id}`);
const adventures = await AdventureModel.findAll(user_id as string | undefined);
console.log(`Fetched ${adventures.length} adventures from the database.`);
// Convert adventures to GeoJSON features
const features: AdventureFeature[] = adventures.map(adventure => {
const parsedPath = typeof adventure.path === 'string'
? JSON.parse(adventure.path)
: adventure.path;
const adventureProperties = adventure.properties || {};
return {
type: 'Feature',
geometry: parsedPath,
properties: {
id: adventure.id,
name: adventure.name,
description: adventure.description,
user_id: adventure.user_id,
recorded_at: adventure.recorded_at,
type: adventureProperties.type || adventureProperties['piste:type'],
difficulty: adventureProperties.difficulty || adventureProperties['piste:difficulty'],
...adventureProperties
}
};
});
const response: AdventureFeatureCollection = {
type: 'FeatureCollection',
features
};
res.json(response);
console.log('--- End getAdventures Controller (Success) ---');
} catch (err) {
console.error('Error in getAdventures:', err);
res.status(500).json({ error: 'Server Error' });
console.log('--- End getAdventures Controller (Error) ---');
}
}
/**
* GET /api/adventures/:id
* Fetch a single adventure by ID
*/
static async getAdventureById(req: Request, res: Response): Promise<void> {
console.log('--- Start getAdventureById Controller ---');
try {
const id = parseInt(req.params.id);
console.log(`Fetching adventure with ID: ${id}`);
const adventure = await AdventureModel.findById(id);
if (!adventure) {
console.log(`Adventure with ID ${id} not found.`);
res.status(404).json({ error: 'Adventure not found' });
return;
}
const parsedPath = typeof adventure.path === 'string'
? JSON.parse(adventure.path)
: adventure.path;
const adventureProperties = adventure.properties || {};
const feature: AdventureFeature = {
type: 'Feature',
geometry: parsedPath,
properties: {
id: adventure.id,
name: adventure.name,
description: adventure.description,
user_id: adventure.user_id,
recorded_at: adventure.recorded_at,
type: adventureProperties.type || adventureProperties['piste:type'],
difficulty: adventureProperties.difficulty || adventureProperties['piste:difficulty'],
...adventureProperties
}
};
res.json(feature);
console.log('--- End getAdventureById Controller (Success) ---');
} catch (err) {
console.error('Error in getAdventureById:', err);
res.status(500).json({ error: 'Server Error' });
console.log('--- End getAdventureById Controller (Error) ---');
}
}
/**
* POST /api/adventures
* Create a new adventure
*/
static async createAdventure(req: Request, res: Response): Promise<void> {
console.log('--- Start createAdventure Controller ---');
try {
const { user_id, name, description, geojson, properties, recorded_at } = req.body;
console.log(`Attempting to create adventure: Name='${name}', User ID='${user_id}'.`);
if (!geojson || !geojson.geometry || !geojson.geometry.coordinates) {
console.error('Validation Error: Invalid or missing GeoJSON in request body.');
res.status(400).json({ error: 'Invalid GeoJSON' });
return;
}
console.log('GeoJSON structure validated.');
const adventureData = {
user_id,
name,
description,
path: geojson.geometry,
properties: geojson.properties || properties,
recorded_at: recorded_at ? new Date(recorded_at) : new Date()
};
const id = await AdventureModel.create(adventureData);
console.log(`Adventure created successfully with ID: ${id}`);
res.json({ success: true, id });
console.log('--- End createAdventure Controller (Success) ---');
} catch (err) {
console.error('Error in createAdventure:', err);
res.status(500).json({ error: 'Server Error' });
console.log('--- End createAdventure Controller (Error) ---');
}
}
/**
* DELETE /api/adventures/:id
* Delete an adventure by ID
*/
static async deleteAdventure(req: Request, res: Response): Promise<void> {
console.log('--- Start deleteAdventure Controller ---');
try {
const id = parseInt(req.params.id);
console.log(`Attempting to delete adventure with ID: ${id}`);
const success = await AdventureModel.delete(id);
if (!success) {
console.log(`Adventure with ID ${id} not found or already deleted.`);
res.status(404).json({ error: 'Adventure not found' });
return;
}
console.log(`Adventure with ID ${id} deleted successfully.`);
res.json({ success: true });
console.log('--- End deleteAdventure Controller (Success) ---');
} catch (err) {
console.error('Error in deleteAdventure:', err);
res.status(500).json({ error: 'Server Error' });
console.log('--- End deleteAdventure Controller (Error) ---');
}
}
}