Skip to content

Commit 4641f9c

Browse files
committed
[di-transaction] Wallet と Inventory を trait に
1 parent 8c66081 commit 4641f9c

File tree

4 files changed

+20
-11
lines changed

4 files changed

+20
-11
lines changed

di-transaction/src/inventory.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@ use mysql;
22
use mysql::params;
33
use mysql::prelude::*;
44

5-
pub struct Inventory {}
5+
pub trait Inventory {
6+
fn add_items(&mut self, tx: &mut mysql::Transaction, amount: i64) -> crate::Result<()>;
7+
}
8+
9+
pub struct MySqlInventory {}
610

7-
impl Inventory {
11+
impl Inventory for MySqlInventory {
812
// アイテムを指定された量だけ追加する
9-
pub fn add_items(&mut self, tx: &mut mysql::Transaction, amount: i64) -> crate::Result<()> {
13+
fn add_items(&mut self, tx: &mut mysql::Transaction, amount: i64) -> crate::Result<()> {
1014
let user_id: i64 = 1;
1115
let item_id: i64 = 1;
1216
let stmt = "\

di-transaction/src/main.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ fn main() -> Result<()> {
1515
let pool = mysql::Pool::new(url)?;
1616
let mut conn = pool.get_conn()?;
1717

18-
let mut inventory = Inventory{};
19-
let mut wallet = Wallet{};
18+
let mut inventory = MySqlInventory{};
19+
let mut wallet = MySqlWallet{};
2020

2121
purchase_item(&mut inventory, &mut wallet, &mut conn)?;
2222

di-transaction/src/purchase.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use anyhow::anyhow;
66

77
// アイテムを購入する
88
pub fn purchase_item(
9-
inventory: &mut Inventory,
10-
wallet: &mut Wallet,
9+
inventory: &mut impl Inventory,
10+
wallet: &mut impl Wallet,
1111
conn: &mut mysql::PooledConn
1212
) -> crate::Result<()> {
1313

di-transaction/src/wallet.rs

+9-4
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,16 @@ use mysql::params;
33
use mysql::prelude::*;
44
use anyhow::anyhow;
55

6-
pub struct Wallet {}
6+
pub trait Wallet {
7+
fn get_balance(&self, tx: &mut mysql::Transaction) -> crate::Result<i64>;
8+
fn pay(&mut self, tx: &mut mysql::Transaction, amount: i64) -> crate::Result<()>;
9+
}
10+
11+
pub struct MySqlWallet {}
712

8-
impl Wallet {
13+
impl Wallet for MySqlWallet {
914
// 現在の残高を返す
10-
pub fn get_balance(&self, tx: &mut mysql::Transaction) -> crate::Result<i64> {
15+
fn get_balance(&self, tx: &mut mysql::Transaction) -> crate::Result<i64> {
1116
let user_id: i64 = 1;
1217
let query = "\
1318
SELECT `balance` \
@@ -21,7 +26,7 @@ impl Wallet {
2126
}
2227

2328
// 残高を減らす
24-
pub fn pay(&mut self, tx: &mut mysql::Transaction, amount: i64) -> crate::Result<()> {
29+
fn pay(&mut self, tx: &mut mysql::Transaction, amount: i64) -> crate::Result<()> {
2530
let user_id: i64 = 1;
2631
let stmt = "\
2732
UPDATE `wallet` \

0 commit comments

Comments
 (0)