feat: initial prototype

This commit is contained in:
əlemi 2023-05-21 18:35:42 +02:00
parent 8dbf31628c
commit 700593a2ea
Signed by: alemi
GPG key ID: A4895B84D311642C
3 changed files with 288 additions and 0 deletions

13
Cargo.toml Normal file
View file

@ -0,0 +1,13 @@
[package]
name = "postwoman"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "4.3.0", features = ["derive"] }
reqwest = { version = "0.11.18", features = ["json"] }
serde = { version = "1.0.163", features = ["derive"] }
serde_json = "1.0.96"
tokio = { version = "1.28.1", features = ["full"] }

146
src/main.rs Normal file
View file

@ -0,0 +1,146 @@
mod model;
use clap::{Parser, Subcommand};
use reqwest::StatusCode;
/// API tester and debugger from your CLI
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct PostWomanArgs {
/// collection to use
#[arg(short, long, default_value = "postwoman.json")]
collection: String,
/// Action to run
#[clap(subcommand)]
action: Option<PostWomanActions>,
/// add action to collection items
#[arg(short = 'S', long, default_value_t = false)]
save: bool,
/// user agent for requests
#[arg(long, default_value = "postwoman")]
agent: String,
}
#[derive(Subcommand, Debug)]
enum PostWomanActions {
/// run a single GET request
Get {
/// request URL
url: String,
/// headers for request
#[arg(short = 'H', long, num_args = 0..)]
headers: Vec<String>,
},
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = PostWomanArgs::parse();
let file = std::fs::File::open(&args.collection)?;
let collection : model::PostWomanCollection = serde_json::from_reader(file)?;
println!("╶┐ * {}", collection.info.name);
println!("{}", collection.info.description);
println!("");
if let Some(action) = args.action {
match action {
PostWomanActions::Get { url, headers } => {
if headers.len() % 2 != 0 {
return Err(PostWomanError::throw("headers must come in pairs"));
}
let mut req = reqwest::Client::new()
.get(url);
for h in headers.chunks(2) {
let (k, v) = (&h[0], &h[1]);
req = req.header(k, v);
}
let res = req.send().await?;
println!("{}", res.text().await?);
}
}
} else {
let mut tasks = Vec::new();
for item in collection.item {
let t = tokio::spawn(async move {
let r = item.exec().await?;
println!("{} >> {}", item.name, r);
Ok::<(), reqwest::Error>(())
});
tasks.push(t);
}
for t in tasks {
t.await??;
}
}
println!("");
Ok(())
}
impl model::Item {
async fn exec(&self) -> reqwest::Result<StatusCode> {
let method = reqwest::Method::from_bytes(
self.request.method.as_bytes()
).unwrap_or(reqwest::Method::GET); // TODO throw an error rather than replacing it silently
let mut req = reqwest::Client::new()
.request(method, self.request.url.to_string());
if let Some(headers) = &self.request.header {
for h in headers {
req = req.header(h.key.clone(), h.value.clone())
}
}
if let Some(body) = &self.request.body {
req = req.body(body.to_string().clone());
}
let res = req.send().await?;
Ok(res.status())
}
}
// barebones custom error
#[derive(Debug)]
struct PostWomanError {
msg : String,
}
impl PostWomanError {
pub fn throw(msg: impl ToString) -> Box<dyn std::error::Error> {
Box::new(
PostWomanError {
msg: msg.to_string(),
}
)
}
}
impl std::fmt::Display for PostWomanError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "PostWomanError({})", self.msg)
}
}
impl std::error::Error for PostWomanError {}

129
src/model.rs Normal file
View file

@ -0,0 +1,129 @@
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
pub struct PostWomanCollection {
pub variables: Vec<String>, // TODO these sure aren't just strings for sure...
pub info: CollectionInfo,
pub item: Vec<Item>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CollectionInfo {
pub name: String,
pub description: String,
pub schema: String,
pub _postman_id: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Item {
pub name: String,
pub event: Option<Vec<Event>>,
pub request: Request,
pub response: Vec<String>, // TODO surely isn't just strings
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Event {
pub listen: String,
pub script: Script,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Script {
pub r#type: String,
pub exec: Vec<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Request {
pub url: Url,
pub method: String,
pub header: Option<Vec<Header>>,
pub body: Option<String>,
pub description: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Header {
pub key: String,
pub value: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Body {
Json(serde_json::Value),
Text(String),
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum Url {
Object {
raw: Option<String>,
protocol: String,
host: Vec<String>,
path: Vec<String>,
query: Option<Vec<Query>>,
variable: Option<Vec<String>>, // TODO surely aren't just strings
},
String(String),
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Query {
pub key: String,
pub value: String,
pub equals: bool,
pub description: Option<String>,
}
impl ToString for Body {
fn to_string(&self) -> String {
match self {
Body::Json(v) => serde_json::to_string(v).unwrap(),
Body::Text(s) => s.clone(),
}
}
}
impl ToString for Query {
fn to_string(&self) -> String {
format!("{}={}", self.key, self.value)
}
}
impl ToString for Url {
fn to_string(&self) -> String {
match self {
Url::String(s) => s.clone(),
Url::Object {
raw, protocol,
host,path, query,
variable: _
} => {
match &raw {
Some(s) => s.clone(),
None => {
let mut url = String::new();
url.push_str(&protocol);
url.push_str("://");
url.push_str(&host.join("."));
url.push_str("/");
url.push_str(&path.join("/"));
if let Some(query) = &query {
url.push_str("?");
let q : Vec<String> = query.iter().map(|x| x.to_string()).collect();
url.push_str(&q.join("&"));
}
url
}
}
}
}
}
}