Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Builder pattern for the services #79

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,39 @@ readme = "./README.md"
license = "MIT"

[dependencies]
chrono = {version = "0.4", optional = true, default-features = false, features = ["clock", "serde"] }
openssl = {version = "0.10", optional = true}
reqwest = {version = "0.11", features = ["json"]}
secrecy = "0.8.0"
serde = {version="1.0", features= ["derive"]}
chrono = { version = "0.4", optional = true, default-features = false, features = [
"clock",
"serde",
] }
openssl = { version = "0.10", optional = true }
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_repr = "0.1"
thiserror = "1.0.37"
wiremock = "0.5"
derive_builder = "0.12"
url = { version = "2", features = ["serde"] }
secrecy = "0.8"


[dev-dependencies]
dotenv = "0.15"
tokio = {version = "1", features = ["rt", "rt-multi-thread", "macros"]}
tokio = { version = "1", features = ["rt", "rt-multi-thread", "macros"] }
wiremock = "0.5"

[features]
default = ["account_balance", "b2b", "b2c", "bill_manager", "c2b_register", "c2b_simulate", "express_request", "transaction_reversal", "transaction_status"]
default = [
"account_balance",
"b2b",
"b2c",
"bill_manager",
"c2b_register",
"c2b_simulate",
"express_request",
"transaction_reversal",
"transaction_status",
]
account_balance = ["dep:openssl"]
b2b = ["dep:openssl"]
b2c = ["dep:openssl"]
Expand All @@ -35,4 +51,4 @@ c2b_register = []
c2b_simulate = []
express_request = ["dep:chrono"]
transaction_reversal = ["dep:openssl"]
transaction_status= ["dep:openssl"]
transaction_status = ["dep:openssl"]
22 changes: 8 additions & 14 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::environment::ApiEnvironment;
use crate::services::{
AccountBalanceBuilder, B2bBuilder, B2cBuilder, BulkInvoiceBuilder, C2bRegisterBuilder,
C2bSimulateBuilder, CancelInvoiceBuilder, MpesaExpressRequestBuilder, OnboardBuilder,
OnboardModifyBuilder, ReconciliationBuilder, SingleInvoiceBuilder, TransactionReversalBuilder,
TransactionStatusBuilder,
C2bSimulateBuilder, CancelInvoiceBuilder, MpesaExpress, MpesaExpressBuilder, OnboardBuilder,
OnboardModifyBuilder, ReconciliationBuilder, SingleInvoiceBuilder, TransactionReversal,
TransactionReversalBuilder, TransactionStatusBuilder,
};
use crate::{ApiError, MpesaError};
use openssl::base64;
Expand Down Expand Up @@ -458,23 +458,17 @@ impl<'mpesa, Env: ApiEnvironment> Mpesa<Env> {
/// .send();
/// ```
#[cfg(feature = "express_request")]
pub fn express_request(
&'mpesa self,
business_short_code: &'mpesa str,
) -> MpesaExpressRequestBuilder<'mpesa, Env> {
MpesaExpressRequestBuilder::new(self, business_short_code)
pub fn express_request(&'mpesa self) -> MpesaExpressBuilder<'mpesa, Env> {
MpesaExpress::builder(self)
}

///**Transaction Reversal Builder**
/// Reverses a B2B, B2C or C2B M-Pesa transaction.
///
/// See more from the Safaricom API docs [here](https://developer.safaricom.co.ke/Documentation)
#[cfg(feature = "transaction_reversal")]
pub fn transaction_reversal(
&'mpesa self,
initiator_name: &'mpesa str,
) -> TransactionReversalBuilder<'mpesa, Env> {
TransactionReversalBuilder::new(self, initiator_name)
pub fn transaction_reversal(&'mpesa self) -> TransactionReversalBuilder<'mpesa, Env> {
TransactionReversal::builder(self)
}

///**Transaction Status Builder**
Expand Down Expand Up @@ -540,7 +534,7 @@ mod tests {
client.set_initiator_password("foo_bar");
assert_eq!(client.initiator_password(), "foo_bar".to_string());
}

#[derive(Clone)]
struct TestEnvironment;

impl ApiEnvironment for TestEnvironment {
Expand Down
2 changes: 1 addition & 1 deletion src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde_repr::{Deserialize_repr, Serialize_repr};
use std::fmt::{Display, Formatter, Result as FmtResult};

/// Mpesa command ids
#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Clone, Deserialize)]
pub enum CommandId {
TransactionReversal,
SalaryPayment,
Expand Down
2 changes: 1 addition & 1 deletion src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub enum Environment {

/// Expected behavior of an `Mpesa` client environment
/// This abstraction exists to make it possible to mock the MPESA api server for tests
pub trait ApiEnvironment {
pub trait ApiEnvironment: Clone {
fn base_url(&self) -> &str;
fn get_certificate(&self) -> &str;
}
Expand Down
33 changes: 31 additions & 2 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use serde::{Deserialize, Serialize};
use std::{env::VarError, fmt};
use thiserror::Error;

/// Mpesa error stack
#[derive(thiserror::Error, Debug)]
#[derive(Error, Debug)]
pub enum MpesaError {
#[error("{0}")]
AuthenticationError(ApiError),
Expand Down Expand Up @@ -44,9 +45,11 @@ pub enum MpesaError {
EncryptionError(#[from] openssl::error::ErrorStack),
#[error("{0}")]
Message(&'static str),
#[error("An error has occurred while building the request: {0}")]
BuilderError(BuilderError),
}

#[derive(Debug, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ApiError {
pub request_id: String,
pub error_code: String,
Expand All @@ -62,3 +65,29 @@ impl fmt::Display for ApiError {
)
}
}

#[derive(Debug, Error)]
pub enum BuilderError {
#[error("Field [{0}] is required")]
UninitializedField(&'static str),
#[error("Field [{0}] is invalid")]
ValidationError(String),
}

impl From<String> for BuilderError {
fn from(s: String) -> Self {
Self::ValidationError(s)
}
}

impl From<derive_builder::UninitializedFieldError> for MpesaError {
fn from(e: derive_builder::UninitializedFieldError) -> Self {
Self::BuilderError(BuilderError::UninitializedField(e.field_name()))
}
}

impl From<url::ParseError> for MpesaError {
fn from(e: url::ParseError) -> Self {
Self::BuilderError(BuilderError::ValidationError(e.to_string()))
}
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ pub use constants::{
};
pub use environment::ApiEnvironment;
pub use environment::Environment::{self, Production, Sandbox};
pub use errors::{ApiError, MpesaError};
pub use errors::{ApiError, BuilderError, MpesaError};
Loading