zero4rs 2.0.0

zero4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use lazy_static::lazy_static;

use serde::{Deserialize, Serialize};

use super::input::PostLocationData;

lazy_static! {
    pub static ref LOCATION_MSG_DB: &'static str = "location_db";
    pub static ref LOCATION_MSG_COL: &'static str = "t_location_msg";
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LocationData {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user: Option<String>,
    pub r#type: String, // gps OR beidou
    pub lat: String,
    pub lng: String,
    pub map: String, // google OR gaode OR baidu
    pub ts1: i64,    // 设备上报时间
    pub ts2: i64,    // 服务端保存时间
    pub late: i32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ext: Option<String>, // ext info
}

impl LocationData {
    pub fn build(curr_user: &str, msg_id: &str, msg: &PostLocationData) -> Self {
        let now = chrono::Utc::now().timestamp_millis();

        Self {
            id: Some(msg_id.to_string()),
            user: Some(curr_user.to_string()),
            r#type: msg.r#type.to_owned(),
            lat: msg.lat.to_owned(),
            lng: msg.lng.to_owned(),
            map: msg.map.to_owned(),
            ts1: msg.ts1,
            ts2: now,
            late: (now - msg.ts1) as i32,
            ext: msg.ext.to_owned(),
        }
    }
}

pub async fn save_location_message(
    ctx: &crate::server::AppContext,
    id: Option<String>,
    curr_user: &str,
    msg: &PostLocationData,
) -> Result<Option<LocationData>, anyhow::Error> {
    if let Some(id) = id {
        let msg = LocationData::build(curr_user, &id, msg);

        if let Some(mongo) = ctx.mongo_opt() {
            let _new_id = mongo
                .insert_one(*LOCATION_MSG_DB, *LOCATION_MSG_COL, msg.clone())
                .await?;

            Ok(Some(msg))
        } else {
            log::warn!("LocationData: id={}, msg=mongo client not enable!", id);
            Ok(None)
        }
    } else {
        Ok(None)
    }
}