aboutsummaryrefslogtreecommitdiffstats
path: root/lib/api-config/src/schema/mod.rs
blob: d1ef5f45c1424ed82bd029b47d9fdb2591b2f5f9 (plain)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
mod create;
pub use create::CreateSchema;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use warden_core::state::AppState;

use crate::ConfigurationError;

/// Transaction to monitor
#[derive(Deserialize, Serialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "utoipa", schema(example = json!({
  "type": "custom.schema",
  "version": "1.0.0",
  "json_schema": {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "title": "FinancialTransaction",
    "type": "object",
    "required": ["transaction_id", "amount", "currency", "timestamp"],
    "properties": {
      "transaction_id": {
        "type": "string",
        "format": "uuid"
      },
      "amount": {
        "type": "number",
        "exclusiveMinimum": 0
      },
      "currency": {
        "type": "string",
        "pattern": "^[A-Z]{3}$",
        "description": "ISO 4217 Alpha-3 code (e.g., USD, EUR)"
      },
      "timestamp": {
        "type": "string",
        "format": "date-time"
      },
    }
  },
  "created_at": time::OffsetDateTime::now_utc().format(&time::format_description::well_known::Rfc3339).unwrap(),
  "updated_at": time::OffsetDateTime::now_utc().format(&time::format_description::well_known::Rfc3339).unwrap(),
})))]
pub struct TransactionSchema {
    #[serde(rename = "type")]
    /// Transaction schema type
    pub kind: String,
    /// The schema's version
    pub version: String,
    /// JSON schema for transcation
    #[serde(rename = "json_schema")]
    pub schema: serde_json::Value,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: OffsetDateTime,
}

#[async_trait]
pub trait SchemaDriver {
    async fn create_schema(
        &self,
        kind: impl AsRef<str> + Send + Sync,
        version: impl AsRef<str> + Send + Sync,
        schema: &serde_json::Value,
    ) -> Result<TransactionSchema, ConfigurationError>;

    async fn delete_schema(
        &self,
        kind: impl AsRef<str> + Send + Sync,
        version: impl AsRef<str> + Send + Sync,
    ) -> Result<(), ConfigurationError>;

    async fn get_schema(
        &self,
        kind: impl AsRef<str> + Send + Sync,
        version: impl AsRef<str> + Send + Sync,
    ) -> Result<Option<TransactionSchema>, ConfigurationError>;

    async fn update_schema(
        &self,
        kind: impl AsRef<str> + Send + Sync,
        version: impl AsRef<str> + Send + Sync,
        schema: &serde_json::Value,
    ) -> Result<TransactionSchema, ConfigurationError>;
}

#[async_trait]
impl SchemaDriver for AppState {
    async fn create_schema(
        &self,
        kind: impl AsRef<str> + Send + Sync,
        version: impl AsRef<str> + Send + Sync,
        schema: &serde_json::Value,
    ) -> Result<TransactionSchema, crate::ConfigurationError> {
        sqlx::query_as!(
            TransactionSchema,
            "insert into transaction_schema (type, version, json_schema) values ($1, $2, $3)
            returning
                type as kind, 
                version, 
                json_schema as schema, 
                created_at, 
                updated_at
        ",
            kind.as_ref(),
            version.as_ref(),
            sqlx::types::Json(&schema) as _
        )
        .fetch_one(&self.database)
        .await
        .map_err(|e| e.into())
    }

    async fn delete_schema(
        &self,
        kind: impl AsRef<str> + Send + Sync,
        version: impl AsRef<str> + Send + Sync,
    ) -> Result<(), crate::ConfigurationError> {
        sqlx::query!(
            "delete from transaction_schema where type = $1 and version = $2",
            kind.as_ref(),
            version.as_ref(),
        )
        .execute(&self.database)
        .await?;
        Ok(())
    }

    async fn get_schema(
        &self,
        kind: impl AsRef<str> + Send + Sync,
        version: impl AsRef<str> + Send + Sync,
    ) -> Result<Option<TransactionSchema>, crate::ConfigurationError> {
        let result = sqlx::query_as!(
            TransactionSchema,
            "select 
                type as kind, 
                version, 
                json_schema as schema, 
                created_at, 
                updated_at
            from transaction_schema where type = $1 and version = $2",
            kind.as_ref(),
            version.as_ref(),
        )
        .fetch_optional(&self.database)
        .await?;

        Ok(result)
    }

    async fn update_schema(
        &self,
        kind: impl AsRef<str> + Send + Sync,
        version: impl AsRef<str> + Send + Sync,
        schema: &serde_json::Value,
    ) -> Result<TransactionSchema, crate::ConfigurationError> {
        sqlx::query_as!(TransactionSchema,
        "
            update
                transaction_schema
            set 
                json_schema = $3
            where 
                type = $1 
                and version = $2
            returning
                type as kind,
                version,
                json_schema as schema,
                created_at,
                updated_at
        ",
            kind.as_ref(),
            version.as_ref(),
            sqlx::types::Json(&schema) as _
        )
        .fetch_one(&self.database)
        .await
        .map_err(|e| e.into())
    }
}