File size: 6,927 Bytes
90a13c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76816cb
 
 
 
 
 
90a13c0
 
76816cb
90a13c0
 
 
 
 
 
76816cb
 
 
90a13c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76816cb
 
 
 
 
 
90a13c0
 
76816cb
90a13c0
 
 
 
 
 
76816cb
 
 
90a13c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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) ---');
        }
    }
}