split bank ad socket server up
This commit is contained in:
parent
3d9c98eeca
commit
c69654a924
22 changed files with 342 additions and 43 deletions
78
socket-server/src/commands/mod.rs
Normal file
78
socket-server/src/commands/mod.rs
Normal file
|
@ -0,0 +1,78 @@
|
|||
use std::collections::HashMap;
|
||||
use std::net::TcpStream;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
use bank::account::AccountError;
|
||||
use bank::bank::Bank;
|
||||
|
||||
use crate::commands::close_account::CloseAccount;
|
||||
use crate::commands::create_account::CreateAccount;
|
||||
use crate::commands::deposit::Deposit;
|
||||
use crate::commands::fail::Fail;
|
||||
use crate::commands::get_account::GetAccount;
|
||||
use crate::commands::get_account_nrs::GetAccountNrs;
|
||||
use crate::commands::pong::Pong;
|
||||
use crate::commands::withdraw::Withdraw;
|
||||
|
||||
mod pong;
|
||||
mod fail;
|
||||
mod close_account;
|
||||
mod create_account;
|
||||
mod deposit;
|
||||
mod get_account;
|
||||
mod get_account_nrs;
|
||||
mod withdraw;
|
||||
|
||||
pub trait Command: Sync + Send {
|
||||
fn execute(&self, bank: Arc<RwLock<Bank>>, data: &[u8], stream: &TcpStream) -> Result<usize>;
|
||||
}
|
||||
|
||||
pub struct Commands {
|
||||
cmds: HashMap<u8, Box<dyn Command>>,
|
||||
}
|
||||
|
||||
struct WebAccountError(AccountError);
|
||||
|
||||
impl From<&WebAccountError> for u8 {
|
||||
fn from(error: &WebAccountError) -> Self {
|
||||
match error.0 {
|
||||
AccountError::Overdraw() => 11,
|
||||
AccountError::Inactive() => 12,
|
||||
AccountError::InvalidAmount() => 13,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error_to_code(error: &AccountError) -> u8 {
|
||||
match error {
|
||||
AccountError::Overdraw() => 11,
|
||||
AccountError::Inactive() => 12,
|
||||
AccountError::InvalidAmount() => 13,
|
||||
}
|
||||
}
|
||||
|
||||
impl Commands {
|
||||
pub fn new() -> Self {
|
||||
let mut cmds = HashMap::new();
|
||||
cmds.insert(1_u8, Box::new(Pong) as Box<dyn Command>);
|
||||
cmds.insert(2_u8, Box::new(CreateAccount) as Box<dyn Command>);
|
||||
cmds.insert(3_u8, Box::new(GetAccount) as Box<dyn Command>);
|
||||
cmds.insert(4_u8, Box::new(GetAccountNrs) as Box<dyn Command>);
|
||||
cmds.insert(5_u8, Box::new(CloseAccount) as Box<dyn Command>);
|
||||
cmds.insert(6_u8, Box::new(Deposit) as Box<dyn Command>);
|
||||
cmds.insert(7_u8, Box::new(Withdraw) as Box<dyn Command>);
|
||||
|
||||
Self {
|
||||
cmds
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&self, bank: Arc<RwLock<Bank>>, cmd: u8, data: &[u8], stream: &TcpStream) -> Result<usize> {
|
||||
match self.cmds.get(&cmd) {
|
||||
None => Fail.execute(bank, &[1_u8], stream),
|
||||
Some(cmd) => cmd.execute(bank, data, stream)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue