Skip to content

Instantly share code, notes, and snippets.

@jayhuang75
Created September 19, 2022 00:34
Show Gist options
  • Save jayhuang75/fd849556adfefa2ee7c6f9ef5614d9af to your computer and use it in GitHub Desktop.
Save jayhuang75/fd849556adfefa2ee7c6f9ef5614d9af to your computer and use it in GitHub Desktop.
rust_serverless_trading_view_db_impl
#[async_trait(?Send)]
pub trait DataStore {
async fn insert(&self, data: &TradingView) -> Result<(), AppError>;
}
#[derive(Debug)]
pub struct AppDB {
// any type inside a Box must implement the Producer trait.
pub db: Box<dyn DataStore>,
}
impl Debug for dyn DataStore {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "DataStore{{{:?}}}", self)
}
}
impl AppDB {
pub async fn insert(&self, data: &TradingView) -> Result<(), AppError> {
if let Err(e) = self.db.insert(data).await {
return Err(AppError {
message: Some(e.to_string()),
cause: Some("aws sdk rdsdata error".to_string()),
error_type: AppErrorType::AwsSdkError,
});
} else {
return Ok(());
}
}
pub fn new(db: Box<dyn DataStore>) -> Self {
AppDB { db }
}
}
#[derive(Debug, Clone)]
pub struct AwsRds {
pub pool: sqlx::Pool<sqlx::Postgres>,
}
impl AwsRds {
pub async fn new() -> Result<Self, AppError> {
let db_pool: sqlx::Pool<sqlx::Postgres> = PgPoolOptions::new()
.max_connections(30)
.connect(&DATABASE_URL)
.await.unwrap();
Ok(AwsRds { pool: db_pool })
}
}
#[async_trait(?Send)]
impl DataStore for AwsRds {
async fn insert(&self, data: &TradingView) -> Result<(), AppError> {
// sqlx insert
}
}
#[cfg(test)]
mod tests {
use crate::db::AppDB;
use super::*;
use dotenv::dotenv;
use tracing::info;
#[tokio::test]
async fn app_db_rds_data() {
dotenv().ok();
//***********************
// Configuration Trading View Alert - Slack
// calling example : trading_view_alert_slack.producer("hello from bot").await;
// //***********************
let new_rds = AwsRds::new().await.unwrap();
let aws_rds = AppDB::new(Box::new(new_rds));
let res = aws_rds
.insert(&TradingView {
name: "NRC".to_string(),
description: "National Research Corporation".to_string(),
update_mode: "delayed_streaming_900".to_string(),
trading_type: "stock".to_string(),
close: 38.66,
price_scale: 100,
min_mov: 1.0,
fractional: "false".to_owned(),
min_mov2: 2.0,
currency: "USD".to_owned(),
change: 1.7468422,
change_abs: 0.66,
recommend_all: 0.5363,
volume: 162997.0,
value_traded: 6301464.0,
})
.await;
let _ = match res {
Ok(()) => {
info!("insert")
},
Err(error) => {
assert_eq!(
error.to_string(),
"insert error"
)
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment