-
Notifications
You must be signed in to change notification settings - Fork 44
/
graphql.rs
92 lines (79 loc) · 2.29 KB
/
graphql.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::str::FromStr;
use async_graphql::*;
use chrono::NaiveDate;
use strum_macros::EnumString;
use crate::get_conn_from_ctx;
use crate::persistence::model::SatelliteEntity;
use crate::persistence::repository;
pub type AppSchema = Schema<Query, EmptyMutation, EmptySubscription>;
pub struct Query;
#[Object]
impl Query {
async fn get_satellites(&self, ctx: &Context<'_>) -> Vec<Satellite> {
repository::get_all(&mut get_conn_from_ctx(ctx))
.expect("Can't get satellites")
.iter()
.map(Satellite::from)
.collect()
}
async fn get_satellite(&self, ctx: &Context<'_>, id: ID) -> Option<Satellite> {
let id = id
.to_string()
.parse::<i32>()
.expect("Can't get id from String");
repository::get(id, &mut get_conn_from_ctx(ctx))
.ok()
.map(|e| Satellite::from(&e))
}
#[graphql(entity)]
async fn get_planet_by_id(&self, id: ID) -> Planet {
Planet { id }
}
}
#[derive(SimpleObject)]
struct Satellite {
id: ID,
name: String,
life_exists: LifeExists,
first_spacecraft_landing_date: Option<NaiveDate>,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Enum, EnumString)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum LifeExists {
Yes,
OpenQuestion,
NoData,
}
struct Planet {
id: ID,
}
#[Object(extends)]
impl Planet {
#[graphql(external)]
async fn id(&self) -> &ID {
&self.id
}
async fn satellites(&self, ctx: &Context<'_>) -> Vec<Satellite> {
let id = self
.id
.to_string()
.parse::<i32>()
.expect("Can't get id from String");
repository::get_by_planet_id(id, &mut get_conn_from_ctx(ctx))
.expect("Can't get satellites of planet")
.iter()
.map(Satellite::from)
.collect()
}
}
impl From<&SatelliteEntity> for Satellite {
fn from(entity: &SatelliteEntity) -> Self {
Satellite {
id: entity.id.into(),
name: entity.name.clone(),
life_exists: LifeExists::from_str(entity.life_exists.as_str())
.expect("Can't convert &str to LifeExists"),
first_spacecraft_landing_date: entity.first_spacecraft_landing_date,
}
}
}