Skip to content

Commit

Permalink
Refactor event model
Browse files Browse the repository at this point in the history
  • Loading branch information
bubelov committed Aug 20, 2024
1 parent e60da98 commit a074c42
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 177 deletions.
102 changes: 11 additions & 91 deletions src/event/model.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@
use crate::Error;
use crate::Result;
use deadpool_sqlite::Pool;
use rusqlite::named_params;
use rusqlite::Connection;
use rusqlite::OptionalExtension;
use rusqlite::Row;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use time::format_description::well_known::Rfc3339;
use time::OffsetDateTime;
use tracing::debug;

pub struct EventRepo {
pool: Arc<Pool>,
}

#[derive(PartialEq, Debug)]
#[derive(Debug, Eq, PartialEq)]
pub struct Event {
pub id: i64,
pub user_id: i64,
Expand All @@ -30,74 +24,6 @@ pub struct Event {
pub deleted_at: Option<OffsetDateTime>,
}

impl EventRepo {
pub fn new(pool: &Arc<Pool>) -> Self {
Self { pool: pool.clone() }
}

#[cfg(test)]
pub async fn insert(&self, user_id: i64, element_id: i64, r#type: &str) -> Result<Event> {
let r#type = r#type.to_string();
self.pool
.get()
.await?
.interact(move |conn| Event::insert(user_id, element_id, &r#type, conn))
.await?
}

pub async fn select_all(
&self,
sort_order: Option<String>,
limit: Option<i64>,
) -> Result<Vec<Event>> {
self.pool
.get()
.await?
.interact(move |conn| Event::select_all(sort_order, limit, conn))
.await?
}

pub async fn select_updated_since(
&self,
updated_since: &OffsetDateTime,
limit: Option<i64>,
) -> Result<Vec<Event>> {
let updated_since = updated_since.clone();
self.pool
.get()
.await?
.interact(move |conn| Event::select_updated_since(&updated_since, limit, conn))
.await?
}

pub async fn select_by_id(&self, id: i64) -> Result<Option<Event>> {
self.pool
.get()
.await?
.interact(move |conn| Event::select_by_id(id, conn))
.await?
}

pub async fn _patch_tags(&self, id: i64, tags: &HashMap<String, Value>) -> Result<Event> {
let tags = tags.clone();
self.pool
.get()
.await?
.interact(move |conn| Event::_patch_tags(id, &tags, conn))
.await?
}

#[cfg(test)]
pub async fn set_updated_at(&self, id: i64, updated_at: &OffsetDateTime) -> Result<Event> {
let updated_at = updated_at.clone();
self.pool
.get()
.await?
.interact(move |conn| Event::_set_updated_at(id, &updated_at, conn))
.await?
}
}

const TABLE: &str = "event";
const _ALL_COLUMNS: &str =
"rowid, user_id, element_id, type, tags, created_at, updated_at, deleted_at";
Expand Down Expand Up @@ -298,12 +224,7 @@ impl Event {
}

#[cfg(test)]
pub fn set_updated_at(&self, updated_at: &OffsetDateTime, conn: &Connection) -> Result<Event> {
Event::_set_updated_at(self.id, updated_at, conn)
}

#[cfg(test)]
pub fn _set_updated_at(
pub fn set_updated_at(
id: i64,
updated_at: &OffsetDateTime,
conn: &Connection,
Expand Down Expand Up @@ -397,15 +318,14 @@ mod test {
let conn = mock_conn();
let user = User::insert(1, &OsmUser::mock(), &conn)?;
let element = Element::insert(&OverpassElement::mock(1), &conn)?;
Event::insert(user.id, element.id, "", &conn)?
.set_updated_at(&datetime!(2020-01-01 00:00 UTC), &conn)?;
let event_1 = Event::insert(user.id, element.id, "", &conn)?;
let _event_1 = Event::set_updated_at(event_1.id, &datetime!(2020-01-01 00:00 UTC), &conn)?;
let event_2 = Event::insert(1, element.id, "", &conn)?;
let event_2 = Event::set_updated_at(event_2.id, &datetime!(2020-01-02 00:00 UTC), &conn)?;
let event_3 = Event::insert(1, element.id, "", &conn)?;
let event_3 = Event::set_updated_at(event_3.id, &datetime!(2020-01-03 00:00 UTC), &conn)?;
assert_eq!(
vec![
Event::insert(1, element.id, "", &conn)?
.set_updated_at(&datetime!(2020-01-02 00:00 UTC), &conn)?,
Event::insert(1, element.id, "", &conn)?
.set_updated_at(&datetime!(2020-01-03 00:00 UTC), &conn)?,
],
vec![event_2, event_3,],
Event::select_updated_since(&datetime!(2020-01-01 00:00 UTC), None, &conn,)?
);
Ok(())
Expand Down Expand Up @@ -453,8 +373,8 @@ mod test {
let updated_at = OffsetDateTime::now_utc();
let user = User::insert(1, &OsmUser::mock(), &conn)?;
let element = Element::insert(&OverpassElement::mock(1), &conn)?;
let event =
Event::insert(user.id, element.id, "", &conn)?.set_updated_at(&updated_at, &conn)?;
let event = Event::insert(user.id, element.id, "", &conn)?;
let event = Event::set_updated_at(event.id, &updated_at, &conn)?;
assert_eq!(
updated_at,
Event::select_by_id(event.id, &conn)?.unwrap().updated_at,
Expand Down
75 changes: 35 additions & 40 deletions src/event/v2.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use super::Event;
use crate::event::model::EventRepo;
use crate::Error;
use actix_web::get;
use actix_web::web::Data;
Expand All @@ -8,10 +7,12 @@ use actix_web::web::Path;
use actix_web::web::Query;
use actix_web::web::Redirect;
use actix_web::Either;
use deadpool_sqlite::Pool;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use time::format_description::well_known::Rfc3339;
use time::Duration;
use time::OffsetDateTime;
Expand Down Expand Up @@ -66,40 +67,39 @@ impl Into<Json<GetItem>> for Event {
#[get("")]
pub async fn get(
args: Query<GetArgs>,
repo: Data<EventRepo>,
pool: Data<Arc<Pool>>,
) -> Result<Either<Json<Vec<GetItem>>, Redirect>, Error> {
if args.limit.is_none() && args.updated_since.is_none() {
return Ok(Either::Right(
Redirect::to("https://static.btcmap.org/api/v2/events.json").permanent(),
));
}

Ok(Either::Left(Json(match &args.updated_since {
Some(updated_since) => repo
.select_updated_since(updated_since, args.limit)
.await?
.into_iter()
.map(|it| it.into())
.collect(),
None => repo
.select_updated_since(
let events = pool
.get()
.await?
.interact(move |conn| match &args.updated_since {
Some(updated_since) => Event::select_updated_since(updated_since, args.limit, conn),
None => Event::select_updated_since(
&OffsetDateTime::now_utc()
.checked_sub(Duration::days(30))
.unwrap(),
args.limit,
)
.await?
.into_iter()
.map(|it| it.into())
.collect(),
})))
conn,
),
})
.await??;
Ok(Either::Left(Json(
events.into_iter().map(|it| it.into()).collect(),
)))
}

#[get("{id}")]
pub async fn get_by_id(id: Path<i64>, repo: Data<EventRepo>) -> Result<Json<GetItem>, Error> {
pub async fn get_by_id(id: Path<i64>, pool: Data<Arc<Pool>>) -> Result<Json<GetItem>, Error> {
let id = id.into_inner();
repo.select_by_id(id)
pool.get()
.await?
.interact(move |conn| Event::select_by_id(id, conn))
.await??
.map(|it| it.into())
.ok_or(Error::HttpNotFound(format!(
"Event with id = {id} doesn't exist"
Expand All @@ -109,6 +109,7 @@ pub async fn get_by_id(id: Path<i64>, repo: Data<EventRepo>) -> Result<Json<GetI
#[cfg(test)]
mod test {
use crate::event::v2::GetItem;
use crate::event::Event;
use crate::osm::osm::OsmUser;
use crate::osm::overpass::OverpassElement;
use crate::test::mock_state;
Expand All @@ -125,7 +126,7 @@ mod test {
let state = mock_state().await;
let app = test::init_service(
App::new()
.app_data(Data::new(state.event_repo))
.app_data(Data::new(state.pool))
.service(scope("/").service(super::get)),
)
.await;
Expand All @@ -140,10 +141,10 @@ mod test {
let state = mock_state().await;
let user = User::insert(1, &OsmUser::mock(), &state.conn)?;
let element = state.element_repo.insert(&OverpassElement::mock(1)).await?;
state.event_repo.insert(user.id, element.id, "").await?;
Event::insert(user.id, element.id, "", &state.conn)?;
let app = test::init_service(
App::new()
.app_data(Data::new(state.event_repo))
.app_data(Data::new(state.pool))
.service(scope("/").service(super::get)),
)
.await;
Expand All @@ -158,12 +159,12 @@ mod test {
let state = mock_state().await;
User::insert(1, &OsmUser::mock(), &state.conn)?;
state.element_repo.insert(&OverpassElement::mock(1)).await?;
state.event_repo.insert(1, 1, "").await?;
state.event_repo.insert(1, 1, "").await?;
state.event_repo.insert(1, 1, "").await?;
Event::insert(1, 1, "", &state.conn)?;
Event::insert(1, 1, "", &state.conn)?;
Event::insert(1, 1, "", &state.conn)?;
let app = test::init_service(
App::new()
.app_data(Data::new(state.event_repo))
.app_data(Data::new(state.pool))
.service(scope("/").service(super::get)),
)
.await;
Expand All @@ -178,19 +179,13 @@ mod test {
let state = mock_state().await;
User::insert(1, &OsmUser::mock(), &state.conn)?;
state.element_repo.insert(&OverpassElement::mock(1)).await?;
let event_1 = state.event_repo.insert(1, 1, "").await?;
state
.event_repo
.set_updated_at(event_1.id, &datetime!(2022-01-05 00:00:00 UTC))
.await?;
let event_2 = state.event_repo.insert(1, 1, "").await?;
state
.event_repo
.set_updated_at(event_2.id, &datetime!(2022-02-05 00:00:00 UTC))
.await?;
let event_1 = Event::insert(1, 1, "", &state.conn)?;
Event::set_updated_at(event_1.id, &datetime!(2022-01-05 00:00:00 UTC), &state.conn)?;
let event_2 = Event::insert(1, 1, "", &state.conn)?;
Event::set_updated_at(event_2.id, &datetime!(2022-02-05 00:00:00 UTC), &state.conn)?;
let app = test::init_service(
App::new()
.app_data(Data::new(state.event_repo))
.app_data(Data::new(state.pool))
.service(scope("/").service(super::get)),
)
.await;
Expand All @@ -208,10 +203,10 @@ mod test {
let event_id = 1;
let user = User::insert(1, &OsmUser::mock(), &state.conn)?;
let element = state.element_repo.insert(&OverpassElement::mock(1)).await?;
state.event_repo.insert(user.id, element.id, "").await?;
Event::insert(user.id, element.id, "", &state.conn)?;
let app = test::init_service(
App::new()
.app_data(Data::new(state.event_repo))
.app_data(Data::new(state.pool))
.service(super::get_by_id),
)
.await;
Expand Down
Loading

0 comments on commit a074c42

Please sign in to comment.