diff --git a/spacetimedb/src/lib.rs b/spacetimedb/src/lib.rs index a60fc94..711fc98 100644 --- a/spacetimedb/src/lib.rs +++ b/spacetimedb/src/lib.rs @@ -435,6 +435,9 @@ pub fn load_messages( continue; } + let created_at = parse_timestamp(item["created_at"].as_str().unwrap_or_default()) + .unwrap_or(ctx.timestamp); + ctx.db.chat_message().insert(ChatMessage { id, channel_id: item["channel_id"].as_str().unwrap_or_default().to_string(), @@ -444,7 +447,7 @@ pub fn load_messages( body: item["body"].as_str().unwrap_or_default().to_string(), message_type: item["message_type"].as_str().unwrap_or("text").to_string(), reply_to: item["reply_to"].as_str().unwrap_or_default().to_string(), - created_at: ctx.timestamp, + created_at, metadata: item["metadata"].as_str().unwrap_or_default().to_string(), edited_at: item["edited_at"].as_str().unwrap_or_default().to_string(), }); @@ -533,6 +536,21 @@ pub fn mark_synced(ctx: &ReducerContext, ids: Vec) -> Result<(), String> { // === Hjelpefunksjoner === +/// Parse en PG-tekststreng ("2026-03-15 23:57:11.677139+00") til SpacetimeDB Timestamp. +fn parse_timestamp(s: &str) -> Option { + if s.is_empty() { return None; } + // Prøv standard ISO-parse først, deretter PG-formater + let dt = s.parse::>() + .map(|d| d.to_utc()) + .or_else(|_| { + chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f") + .or_else(|_| chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")) + .map(|naive| naive.and_utc()) + }) + .ok()?; + Some(Timestamp::from_micros_since_unix_epoch(dt.timestamp_micros())) +} + /// Formater en SpacetimeDB Timestamp til ISO 8601-streng. fn format_timestamp(ts: Timestamp) -> String { let duration = ts.to_duration_since_unix_epoch().unwrap_or_default();