use {
crate::{
Address,
Envelope,
Protocol,
Result,
},
bytes::Bytes,
};
pub trait Gateway {
fn address(&self) -> &Address;
fn protocol(&self) -> &Protocol;
fn handle(&self, path: &str, data: Bytes) -> Result<Envelope>;
}
#[cfg(test)]
mod tests {
use {
super::*,
crate::Payload,
};
const URI: &str = "https://gateway.com";
pub struct BasicGateway {
address: Address,
protocol: Protocol,
}
impl BasicGateway {
pub fn new(addr: &str, proto: &str) -> Result<Self> {
Ok(Self {
address: Address::parse(addr)?,
protocol: proto.into(),
})
}
}
impl Gateway for BasicGateway {
fn address(&self) -> &Address { &self.address }
fn protocol(&self) -> &Protocol { &self.protocol }
fn handle(&self, path: &str, data: Bytes) -> Result<Envelope> {
let destination = Address::parse(format!("{}:/{}", self.protocol, path))?;
let message = Envelope::new(self.address().clone(), destination, data);
Ok(message)
}
}
#[test]
fn basic_gateway() -> Result<()> {
let gateway = BasicGateway::new(URI, "grpc")?;
assert_eq!(gateway.address().to_string(), URI);
assert_eq!(gateway.protocol().as_ref(), "grpc");
Ok(())
}
#[test]
fn gateway_handle() -> Result<()> {
let path = "/users";
let data = Payload::from("Hello, World!");
let gateway = BasicGateway::new(URI, "http")?;
let msg = gateway.handle(path, data.clone())?;
assert_eq!(msg.source().to_string(), URI);
assert_eq!(msg.destination().to_string(), "http://users");
assert_eq!(msg.payload(), &data);
Ok(())
}
}