summaryrefslogtreecommitdiff
path: root/src/graphql/mutation.rs
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2024-08-24 21:42:01 +0200
committerSanto Cariotti <santo@dcariotti.me>2024-08-24 21:42:01 +0200
commit8d36b0b75904812ba8f6b9e38b50660dfbe78d0d (patch)
tree2b9a3b4e0df111b4a6ff94b7d1b7be43c9efdaf8 /src/graphql/mutation.rs
parentd1160f2aa59db4489aad506aaa063be4966609ce (diff)
Add new position
``` curl -X POST http://localhost:8000/graphql \ -H "Content-Type: application/json" \ -H "Authorization: Bearer TOKEN" \ -d '{ "query": "mutation NewPosition($input: PositionInput!) { newPosition(input: $input) { id userId createdAt latitude longitude movingActivity } }", "variables": { "input": { "latitude": 44.502952, "longitude": 11.3114988, "movingActivity": "IN_VEHICLE" } } }' ```
Diffstat (limited to 'src/graphql/mutation.rs')
-rw-r--r--src/graphql/mutation.rs61
1 files changed, 59 insertions, 2 deletions
diff --git a/src/graphql/mutation.rs b/src/graphql/mutation.rs
index 9cee796..5a93038 100644
--- a/src/graphql/mutation.rs
+++ b/src/graphql/mutation.rs
@@ -1,6 +1,13 @@
-use crate::graphql::types::jwt;
-use crate::state::AppState;
+use crate::{
+ dates::GraphQLDate,
+ graphql::types::{
+ jwt::{self, Authentication},
+ position,
+ },
+ state::AppState,
+};
use async_graphql::{Context, Error, FieldResult, Object};
+use chrono::Utc;
/// Mutation struct
pub struct Mutation;
@@ -35,4 +42,54 @@ impl Mutation {
Err(Error::new("Invalid email or password"))
}
}
+
+ /// Make GraphQL request to create new position to track
+ async fn new_position<'ctx>(
+ &self,
+ ctx: &Context<'ctx>,
+ input: position::PositionInput,
+ ) -> FieldResult<position::Position> {
+ let state = ctx.data::<AppState>().expect("Can't connect to db");
+ let client = &*state.client;
+
+ let auth: &Authentication = ctx.data().unwrap();
+ match auth {
+ Authentication::NotLogged => Err(Error::new("Can't find the owner")),
+ Authentication::Logged(claims) => {
+ let rows = client
+ .query(
+ "INSERT INTO positions (user_id, location, activity)
+ VALUES (
+ $1,
+ ST_SetSRID(ST_MakePoint($2, $3), 4326),
+ $4
+ )
+ RETURNING id, user_id, created_at, ST_Y(location::geometry) AS latitude, ST_X(location::geometry) AS longitude, activity
+ ",
+ &[
+ &claims.user_id,
+ &input.latitude,
+ &input.longitude,
+ &input.moving_activity,
+ ],
+ )
+ .await
+ .unwrap();
+
+ let positions: Vec<position::Position> = rows
+ .iter()
+ .map(|row| position::Position {
+ id: row.get("id"),
+ user_id: row.get("user_id"),
+ created_at: GraphQLDate(Utc::now()),
+ latitude: row.get("latitude"),
+ longitude: row.get("longitude"),
+ moving_activity: row.get("activity"),
+ })
+ .collect();
+
+ Ok(positions[0].clone())
+ }
+ }
+ }
}