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
use async_graphql::{types::connection::*, *};
use serde::{Deserialize, Serialize};

use super::{convert::ToGlobalId, primitives::*};

#[derive(SimpleObject)]
pub struct Job {
    pub id: ID,
    pub job_id: UUID,
    pub name: String,
    pub description: Option<String>,
}

#[derive(SimpleObject)]
pub struct JobCreatePayload {
    pub job: Job,
}

#[derive(Serialize, Deserialize)]
pub(super) struct JobByNameCursor {
    pub name: String,
    pub id: crate::primitives::JobId,
}

impl CursorType for JobByNameCursor {
    type Error = String;

    fn encode_cursor(&self) -> String {
        use base64::{engine::general_purpose, Engine as _};
        let json = serde_json::to_string(&self).expect("could not serialize token");
        general_purpose::STANDARD_NO_PAD.encode(json.as_bytes())
    }

    fn decode_cursor(s: &str) -> Result<Self, Self::Error> {
        use base64::{engine::general_purpose, Engine as _};
        let bytes = general_purpose::STANDARD_NO_PAD
            .decode(s.as_bytes())
            .map_err(|e| e.to_string())?;
        let json = String::from_utf8(bytes).map_err(|e| e.to_string())?;
        serde_json::from_str(&json).map_err(|e| e.to_string())
    }
}

impl ToGlobalId for crate::primitives::JobId {
    fn to_global_id(&self) -> async_graphql::types::ID {
        async_graphql::types::ID::from(format!("job:{}", self))
    }
}

impl From<JobByNameCursor> for crate::job::JobByNameCursor {
    fn from(cursor: JobByNameCursor) -> Self {
        Self {
            name: cursor.name,
            id: cursor.id,
        }
    }
}

impl From<&crate::job::Job> for JobByNameCursor {
    fn from(job: &crate::job::Job) -> Self {
        Self {
            name: job.name.clone(),
            id: job.id,
        }
    }
}

impl From<crate::job::Job> for Job {
    fn from(job: crate::job::Job) -> Self {
        Self {
            id: job.id.to_global_id(),
            job_id: UUID::from(job.id),
            name: job.name,
            description: job.description,
        }
    }
}