Skip to content
This repository has been archived by the owner on Aug 3, 2023. It is now read-only.

Commit

Permalink
Merge pull request #65 from cloudflare/route
Browse files Browse the repository at this point in the history
route
  • Loading branch information
ashleygwilliams authored Apr 10, 2019
2 parents f91b291 + 84291b4 commit 9d4f331
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 16 deletions.
12 changes: 9 additions & 3 deletions src/commands/publish/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod krate;
pub mod preview;
mod route;
use route::Route;

use std::fs;
use std::path::Path;
Expand All @@ -8,19 +10,25 @@ use crate::user::User;

use reqwest::multipart::Form;

pub fn publish(user: &User, name: Option<&str>) -> Result<(), failure::Error> {
pub fn publish(user: User, name: Option<&str>) -> Result<(), failure::Error> {
if user.account.multiscript {
if name.is_none() {
println!("⚠️ You have multiscript account. Using a default name, 'wasm-worker'.")
}
let name = name.unwrap_or("wasm-worker");
multi_script(&user, name)?;
Route::create(&user, Some(name.to_string()))?;
} else {
if name.is_some() {
println!("⚠️ You only have a single script account. Ignoring name.")
}
single_script(&user)?;
Route::create(&user, None)?;
}
println!(
"✨ Success! Your worker was successfully published. You can view it at {}. ✨",
user.settings.project.route.unwrap()
);
Ok(())
}

Expand All @@ -41,7 +49,6 @@ fn single_script(user: &User) -> Result<(), failure::Error> {
.multipart(build_form()?)
.send()?;

println!("✨ Success! Your worker was successfully published. ✨",);
Ok(())
}

Expand All @@ -62,7 +69,6 @@ fn multi_script(user: &User, name: &str) -> Result<(), failure::Error> {
.multipart(build_form()?)
.send()?;

println!("✨ Success! Your worker was successfully published. ✨",);
Ok(())
}

Expand Down
91 changes: 91 additions & 0 deletions src/commands/publish/route.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use crate::user::User;
use reqwest::header::CONTENT_TYPE;
use serde::Serialize;

#[derive(Serialize)]
pub struct Route {
#[serde(skip_serializing_if = "Option::is_none")]
enabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
script: Option<String>,
pattern: String,
}

impl Route {
pub fn create(user: &User, script: Option<String>) -> Result<Route, failure::Error> {
if user.account.multiscript {
match script {
Some(s) => multi_script(user, s),
None => failure::bail!("⚠️ You must provide the name of the script you'd like to associate with this route."),
}
} else {
if script.is_some() {
println!("⚠️ You only have a single script account. Ignoring name.");
}
single_script(user)
}
}
}

fn multi_script(user: &User, script: String) -> Result<Route, failure::Error> {
let pattern = &user.settings.clone().project.route.expect("⚠️ Your project config has an error, check your `wrangler.toml`: `route` must be provided.");
let route = Route {
script: Some(script),
pattern: pattern.to_string(),
enabled: None,
};
let zone_id = &user.settings.project.zone_id;
let routes_addr = format!(
"https://api.cloudflare.com/client/v4/zones/{}/workers/routes",
zone_id
);

let client = reqwest::Client::new();
let settings = user.settings.to_owned();
let body = serde_json::to_string(&route)?;

let mut res = client
.post(&routes_addr)
.header("X-Auth-Key", settings.global_user.api_key)
.header("X-Auth-Email", settings.global_user.email)
.header(CONTENT_TYPE, "application/json")
.body(body)
.send()?;

if !res.status().is_success() {
let msg = format!(
"⛔ There was an error creating your route.\n Status Code: {}\n Msg: {}",
res.status(),
res.text()?
);
failure::bail!(msg)
}
Ok(route)
}

fn single_script(user: &User) -> Result<Route, failure::Error> {
let pattern = user.settings.clone().project.route.expect("⚠️ Your project config has an error, check your `wrangler.toml`: `route` must be provided.");
let route = Route {
script: None,
pattern,
enabled: Some(true),
};
let zone_id = &user.settings.project.zone_id;
let filters_addr = format!(
"https://api.cloudflare.com/client/v4/zones/{}/workers/filters",
zone_id
);

let client = reqwest::Client::new();
let settings = user.settings.to_owned();

client
.put(&filters_addr)
.header("X-Auth-Key", settings.global_user.api_key)
.header("X-Auth-Email", settings.global_user.email)
.header(CONTENT_TYPE, "application/json")
.body(serde_json::to_string(&route)?)
.send()?;

Ok(route)
}
5 changes: 1 addition & 4 deletions src/commands/whoami.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,5 @@ use crate::user::User;
pub fn whoami(user: &User) {
let user = &user.data;

println!(
"👋 You are logged in as {} {}, with the email '{}'.",
user.first_name, user.last_name, user.email
);
println!("👋 You are logged with the email '{}'.", user.email);
}
12 changes: 6 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ fn main() -> Result<(), failure::Error> {
.arg(
Arg::with_name("name")
.help("(optional) For multiscript users, provide a script name")
.index(2)
.index(1)
),
)
.subcommand(
Expand Down Expand Up @@ -119,15 +119,15 @@ fn main() -> Result<(), failure::Error> {
} else {
let user = User::new()?;

if matches.subcommand_matches("whoami").is_some() {
commands::whoami(&user);
}

if let Some(matches) = matches.subcommand_matches("publish") {
let name = matches.value_of("name");

commands::build(&cache)?;
commands::publish(&user, name)?;
}

if matches.subcommand_matches("whoami").is_some() {
commands::whoami(&user);
commands::publish(user, name)?;
}
}
Ok(())
Expand Down
3 changes: 0 additions & 3 deletions src/user/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@ pub struct UserResponse {
#[derive(Debug, Deserialize)]
pub struct UserData {
pub email: String,
pub first_name: String,
pub last_name: String,
pub username: String,
}

impl User {
Expand Down

0 comments on commit 9d4f331

Please sign in to comment.