Skip to content

Commit

Permalink
Merge pull request #199 from starknet-id/ayush/unique-page-visit
Browse files Browse the repository at this point in the history
feat: add unique page visit endpoint
  • Loading branch information
Th0rgal authored Mar 8, 2024
2 parents ea2a1ce + c3d25cd commit 047dd7f
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ chrono = "0.4.19"
lazy_static = "1.4.0"
regex = "1.10.0"
ctor = "0.2.6"
axum-client-ip = "0.4.0"
3 changes: 2 additions & 1 deletion src/endpoints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ pub mod leaderboard;
pub mod quest_boost;
pub mod quests;
pub mod get_boosted_quests;
pub mod analytics;
pub mod analytics;
pub mod unique_page_visit;
47 changes: 47 additions & 0 deletions src/endpoints/unique_page_visit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use crate::{
models::{AppState},
utils::get_error,
};
use axum::{
extract::{Query, State},
http::StatusCode,
response::IntoResponse,
Json,
};
use axum_auto_routes::route;
use mongodb::bson::doc;
use serde::Deserialize;
use std::sync::Arc;
use chrono::Utc;
use mongodb::Collection;
use mongodb::options::UpdateOptions;
use serde_json::json;
use crate::models::UniquePageVisit;
use axum_client_ip::InsecureClientIp;

#[derive(Deserialize)]
pub struct GetQuestsQuery {
page_id: String,
}

#[route(get, "/unique_page_visit", crate::endpoints::unique_page_visit)]
pub async fn handler(
insecure_ip: InsecureClientIp,
State(state): State<Arc<AppState>>,
Query(query): Query<GetQuestsQuery>,
) -> impl IntoResponse {
let addr = insecure_ip.0;
let id = query.page_id;
let unique_viewers_collection: Collection<UniquePageVisit> =
state.db.collection("unique_viewers");
let created_at = Utc::now().timestamp_millis();
let filter = doc! { "viewer_ip": addr.to_string(), "viewed_page_id": &id };
let update = doc! { "$setOnInsert": { "viewer_ip": addr.to_string(), "viewed_page_id": &id,"timestamp":created_at } };
let options = UpdateOptions::builder().upsert(true).build();

match unique_viewers_collection.update_one(filter, update, options)
.await {
Ok(_) => (StatusCode::OK, Json(json!({"res": true}))).into_response(),
Err(_) => get_error("unable to detect page visit status".to_string()),
}
}

0 comments on commit 047dd7f

Please sign in to comment.