ridewithgps-client 0.1.0

API client for the RideWithGPS routing and trip planning service
Documentation
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Event-related types and methods

use crate::{PaginatedResponse, Photo, Result, RideWithGpsClient, Visibility};
use serde::{Deserialize, Serialize};

/// Event organizer information
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Organizer {
    /// Organizer ID
    pub id: Option<u64>,

    /// Organizer name
    pub name: Option<String>,

    /// Created timestamp
    pub created_at: Option<String>,

    /// Updated timestamp
    pub updated_at: Option<String>,
}

/// An event
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Event {
    /// Event ID
    pub id: u64,

    /// Event name
    pub name: Option<String>,

    /// Event description
    pub description: Option<String>,

    /// Event location
    pub location: Option<String>,

    /// Latitude
    pub lat: Option<f64>,

    /// Longitude
    pub lng: Option<f64>,

    /// Event visibility
    pub visibility: Option<Visibility>,

    /// API URL
    pub url: Option<String>,

    /// HTML/web URL
    pub html_url: Option<String>,

    /// Time zone
    pub time_zone: Option<String>,

    /// Start date
    pub start_date: Option<String>,

    /// Start time (e.g., "09:00")
    pub start_time: Option<String>,

    /// End date
    pub end_date: Option<String>,

    /// End time (e.g., "17:00")
    pub end_time: Option<String>,

    /// Whether it's an all-day event
    pub all_day: Option<bool>,

    /// Event start date/time (combined)
    pub starts_at: Option<String>,

    /// Event end date/time (combined)
    pub ends_at: Option<String>,

    /// Registration opens at
    pub registration_opens_at: Option<String>,

    /// Registration closes at
    pub registration_closes_at: Option<String>,

    /// User ID of the event owner
    pub user_id: Option<u64>,

    /// Created timestamp
    pub created_at: Option<String>,

    /// Updated timestamp
    pub updated_at: Option<String>,

    /// Event URL slug
    pub slug: Option<String>,

    /// Logo URL
    pub logo_url: Option<String>,

    /// Banner URL
    pub banner_url: Option<String>,

    /// Whether registration is required
    pub registration_required: Option<bool>,

    /// Maximum attendees
    pub max_attendees: Option<u32>,

    /// Current number of attendees
    pub attendee_count: Option<u32>,

    /// Event organizers (included when fetching a specific event)
    pub organizers: Option<Vec<Organizer>>,

    /// Photos (included when fetching a specific event)
    pub photos: Option<Vec<Photo>>,
}

/// Parameters for listing events
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListEventsParams {
    /// Filter by event name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Filter by visibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,

    /// Page number
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,

    /// Page size
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page_size: Option<u32>,
}

/// Request to create or update an event
#[derive(Debug, Clone, Serialize)]
pub struct EventRequest {
    /// Event name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Event description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Event location
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,

    /// Event visibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,

    /// Event start date/time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub starts_at: Option<String>,

    /// Event end date/time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ends_at: Option<String>,

    /// Registration opens at
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registration_opens_at: Option<String>,

    /// Registration closes at
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registration_closes_at: Option<String>,

    /// Whether registration is required
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registration_required: Option<bool>,

    /// Maximum attendees
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_attendees: Option<u32>,
}

impl RideWithGpsClient {
    /// List events
    ///
    /// # Arguments
    ///
    /// * `params` - Optional parameters for filtering and pagination
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ridewithgps_client::{RideWithGpsClient, ListEventsParams};
    ///
    /// let client = RideWithGpsClient::new(
    ///     "https://ridewithgps.com",
    ///     "your-api-key",
    ///     Some("your-auth-token")
    /// );
    ///
    /// let events = client.list_events(None).unwrap();
    /// println!("Found {} events", events.results.len());
    /// ```
    pub fn list_events(
        &self,
        params: Option<&ListEventsParams>,
    ) -> Result<PaginatedResponse<Event>> {
        let mut url = "/api/v1/events.json".to_string();

        if let Some(params) = params {
            let query = serde_json::to_value(params)?;
            if let Some(obj) = query.as_object() {
                if !obj.is_empty() {
                    let query_str = serde_urlencoded::to_string(obj).map_err(|e| {
                        crate::Error::ApiError(format!("Failed to encode query: {}", e))
                    })?;
                    url.push('?');
                    url.push_str(&query_str);
                }
            }
        }

        self.get(&url)
    }

    /// Create a new event
    ///
    /// # Arguments
    ///
    /// * `event` - The event data
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ridewithgps_client::{RideWithGpsClient, EventRequest, Visibility};
    ///
    /// let client = RideWithGpsClient::new(
    ///     "https://ridewithgps.com",
    ///     "your-api-key",
    ///     Some("your-auth-token")
    /// );
    ///
    /// let event_req = EventRequest {
    ///     name: Some("My Event".to_string()),
    ///     description: Some("A great ride".to_string()),
    ///     location: Some("San Francisco, CA".to_string()),
    ///     visibility: Some(Visibility::Public),
    ///     starts_at: Some("2025-06-01T09:00:00".to_string()),
    ///     ends_at: Some("2025-06-01T17:00:00".to_string()),
    ///     registration_opens_at: None,
    ///     registration_closes_at: None,
    ///     registration_required: Some(false),
    ///     max_attendees: None,
    /// };
    ///
    /// let event = client.create_event(&event_req).unwrap();
    /// println!("Created event: {}", event.id);
    /// ```
    pub fn create_event(&self, event: &EventRequest) -> Result<Event> {
        #[derive(Deserialize)]
        struct EventWrapper {
            event: Event,
        }

        let wrapper: EventWrapper = self.post("/api/v1/events.json", event)?;
        Ok(wrapper.event)
    }

    /// Get a specific event by ID
    ///
    /// # Arguments
    ///
    /// * `id` - The event ID
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ridewithgps_client::RideWithGpsClient;
    ///
    /// let client = RideWithGpsClient::new(
    ///     "https://ridewithgps.com",
    ///     "your-api-key",
    ///     None
    /// );
    ///
    /// let event = client.get_event(12345).unwrap();
    /// println!("Event: {:?}", event);
    /// ```
    pub fn get_event(&self, id: u64) -> Result<Event> {
        #[derive(Deserialize)]
        struct EventWrapper {
            event: Event,
        }

        let wrapper: EventWrapper = self.get(&format!("/api/v1/events/{}.json", id))?;
        Ok(wrapper.event)
    }

    /// Update an event
    ///
    /// # Arguments
    ///
    /// * `id` - The event ID
    /// * `event` - The updated event data
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ridewithgps_client::{RideWithGpsClient, EventRequest};
    ///
    /// let client = RideWithGpsClient::new(
    ///     "https://ridewithgps.com",
    ///     "your-api-key",
    ///     Some("your-auth-token")
    /// );
    ///
    /// let event_req = EventRequest {
    ///     name: Some("Updated Event Name".to_string()),
    ///     description: None,
    ///     location: None,
    ///     visibility: None,
    ///     starts_at: None,
    ///     ends_at: None,
    ///     registration_opens_at: None,
    ///     registration_closes_at: None,
    ///     registration_required: None,
    ///     max_attendees: None,
    /// };
    ///
    /// let event = client.update_event(12345, &event_req).unwrap();
    /// println!("Updated event: {:?}", event);
    /// ```
    pub fn update_event(&self, id: u64, event: &EventRequest) -> Result<Event> {
        #[derive(Deserialize)]
        struct EventWrapper {
            event: Event,
        }

        let wrapper: EventWrapper = self.put(&format!("/api/v1/events/{}.json", id), event)?;
        Ok(wrapper.event)
    }

    /// Delete an event
    ///
    /// # Arguments
    ///
    /// * `id` - The event ID
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ridewithgps_client::RideWithGpsClient;
    ///
    /// let client = RideWithGpsClient::new(
    ///     "https://ridewithgps.com",
    ///     "your-api-key",
    ///     Some("your-auth-token")
    /// );
    ///
    /// client.delete_event(12345).unwrap();
    /// ```
    pub fn delete_event(&self, id: u64) -> Result<()> {
        self.delete(&format!("/api/v1/events/{}.json", id))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_event_deserialization() {
        let json = r#"{
            "id": 789,
            "name": "Test Event",
            "location": "Portland, OR",
            "visibility": "public",
            "starts_at": "2025-06-01T09:00:00",
            "attendee_count": 25
        }"#;

        let event: Event = serde_json::from_str(json).unwrap();
        assert_eq!(event.id, 789);
        assert_eq!(event.name.as_deref(), Some("Test Event"));
        assert_eq!(event.location.as_deref(), Some("Portland, OR"));
        assert_eq!(event.visibility, Some(Visibility::Public));
        assert_eq!(event.attendee_count, Some(25));
    }

    #[test]
    fn test_event_request_serialization() {
        let req = EventRequest {
            name: Some("My Event".to_string()),
            description: Some("Fun ride".to_string()),
            location: None,
            visibility: Some(Visibility::Public),
            starts_at: None,
            ends_at: None,
            registration_opens_at: None,
            registration_closes_at: None,
            registration_required: Some(true),
            max_attendees: Some(100),
        };

        let json = serde_json::to_value(&req).unwrap();
        assert_eq!(json.get("name").unwrap(), "My Event");
        assert_eq!(json.get("visibility").unwrap(), "public");
        assert_eq!(json.get("registration_required").unwrap(), true);
        assert_eq!(json.get("max_attendees").unwrap(), 100);
    }

    #[test]
    fn test_event_wrapper_deserialization() {
        let json = r#"{
            "event": {
                "id": 999,
                "name": "Wrapped Event",
                "location": "Portland, OR",
                "visibility": "public"
            }
        }"#;

        #[derive(Deserialize)]
        struct EventWrapper {
            event: Event,
        }

        let wrapper: EventWrapper = serde_json::from_str(json).unwrap();
        assert_eq!(wrapper.event.id, 999);
        assert_eq!(wrapper.event.name.as_deref(), Some("Wrapped Event"));
        assert_eq!(wrapper.event.location.as_deref(), Some("Portland, OR"));
    }

    #[test]
    fn test_event_with_dates_and_times() {
        let json = r#"{
            "id": 555,
            "name": "Time Test Event",
            "start_date": "2025-06-01",
            "start_time": "09:00",
            "end_date": "2025-06-01",
            "end_time": "17:00",
            "all_day": false,
            "time_zone": "America/Los_Angeles",
            "starts_at": "2025-06-01T09:00:00-07:00",
            "ends_at": "2025-06-01T17:00:00-07:00"
        }"#;

        let event: Event = serde_json::from_str(json).unwrap();
        assert_eq!(event.id, 555);
        assert_eq!(event.start_date.as_deref(), Some("2025-06-01"));
        assert_eq!(event.start_time.as_deref(), Some("09:00"));
        assert_eq!(event.all_day, Some(false));
        assert_eq!(event.time_zone.as_deref(), Some("America/Los_Angeles"));
    }

    #[test]
    fn test_organizer_deserialization() {
        let json = r#"{
            "id": 42,
            "name": "Bike Club",
            "created_at": "2020-01-01T00:00:00Z"
        }"#;

        let organizer: Organizer = serde_json::from_str(json).unwrap();
        assert_eq!(organizer.id, Some(42));
        assert_eq!(organizer.name.as_deref(), Some("Bike Club"));
    }
}