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

Implement create/update and list Workers endpoints #106

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
53 changes: 53 additions & 0 deletions cloudflare-examples/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,44 @@ fn list_routes<ApiClientType: ApiClient>(arg_matches: &ArgMatches, api_client: &
print_response_json(response);
}

fn list_scripts<ApiClientType: ApiClient>(arg_matches: &ArgMatches, api_client: &ApiClientType) {
let usage = "usage: list_scripts ACCOUNT_ID";

let account_id_missing = format!("missing '{}': {}", "ACCOUNT_ID", usage);
let account_identifier = arg_matches
.value_of("account_identifier")
.expect(&account_id_missing);

let response = api_client.request(&workers::ListScripts { account_identifier });

print_response_json(response);
}


fn create_script<ApiClientType: ApiClient>(arg_matches: &ArgMatches, api_client: &ApiClientType) {
let usage = "usage: create_script ACCOUNT_ID SCRIPT_NAME";

let script_name_missing = format!("missing '{}': {}", "SCRIPT_NAME", usage);
let script_name = arg_matches
.value_of("script_name")
.expect(&script_name_missing);

let script_content = String::from("addEventListener('fetch', event => { event.respondWith(fetch(event.request)) })");

let account_id_missing = format!("missing '{}': {}", "ACCOUNT_ID", usage);
let account_identifier = arg_matches
.value_of("account_identifier")
.expect(&account_id_missing);

let response = api_client.request(&workers::CreateScript {
account_identifier,
script_name,
script_content,
});

print_response_json(response);
}

fn list_accounts<ApiClientType: ApiClient>(_arg_matches: &ArgMatches, api_client: &ApiClientType) {
let response = api_client.request(&account::ListAccounts { params: None });

Expand Down Expand Up @@ -228,6 +266,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
description: "Activate a Worker on a Route",
function: list_routes
},
"list_scripts" => Section{
args: vec![
Arg::with_name("account_identifier").required(true),
],
description: "List Workers on an account",
function: list_scripts
},
"create_script" => Section{
args: vec![
Arg::with_name("account_identifier").required(true),
Arg::with_name("script_name").required(true),
],
description: "Create or update a Worker",
function: create_script
},
"list_accounts" => Section{
args: vec![],
description: "List accounts",
Expand Down
30 changes: 30 additions & 0 deletions cloudflare/src/endpoints/workers/create_script.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use super::WorkersScript;

use crate::framework::endpoint::{Endpoint, Method};

/// Create Script
/// Create or update a Worker Script.
/// https://api.cloudflare.com/#worker-script-upload-worker
pub struct CreateScript<'a> {
pub account_identifier: &'a str,
pub script_name: &'a str,
pub script_content: String,
}

impl<'a> Endpoint<WorkersScript, (), String> for CreateScript<'a> {
fn method(&self) -> Method {
Method::Put
}
fn path(&self) -> String {
format!(
"accounts/{}/workers/scripts/{}",
self.account_identifier, self.script_name
)
}
fn serialized_body(&self) -> Option<String> {
Some(self.script_content.clone())
}
fn content_type(&self) -> String {
"application/javascript".to_owned()
}
}
22 changes: 22 additions & 0 deletions cloudflare/src/endpoints/workers/list_scripts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use super::WorkersScript;

use crate::framework::endpoint::{Endpoint, Method};

/// List Scripts
/// Lists all scripts for a given account
/// https://api.cloudflare.com/#worker-script-list-workers
pub struct ListScripts<'a> {
pub account_identifier: &'a str,
}

impl<'a> Endpoint<Vec<WorkersScript>> for ListScripts<'a> {
fn method(&self) -> Method {
Method::Get
}
fn path(&self) -> String {
format!(
"accounts/{}/workers/scripts",
self.account_identifier
)
}
}
16 changes: 16 additions & 0 deletions cloudflare/src/endpoints/workers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,21 @@ use serde::Deserialize;

mod create_route;
mod create_secret;
mod create_script;
mod delete_route;
mod delete_secret;
mod list_routes;
mod list_secrets;
mod list_scripts;

pub use create_route::{CreateRoute, CreateRouteParams};
pub use create_secret::{CreateSecret, CreateSecretParams};
pub use create_script::{CreateScript};
pub use delete_route::DeleteRoute;
pub use delete_secret::DeleteSecret;
pub use list_routes::ListRoutes;
pub use list_secrets::ListSecrets;
pub use list_scripts::ListScripts;

/// Workers KV Route
/// Routes are basic patterns used to enable or disable workers that match requests.
Expand Down Expand Up @@ -60,3 +64,15 @@ pub struct WorkersSecret {

impl ApiResult for WorkersSecret {}
impl ApiResult for Vec<WorkersSecret> {} // to parse arrays too

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct WorkersScript {
pub id: String,
pub etag: String,
pub script: Option<String>,
pub size: Option<u32>,
pub created_on: Option<DateTime<Utc>>,
pub modified_on: DateTime<Utc>,
}
impl ApiResult for WorkersScript {}
impl ApiResult for Vec<WorkersScript> {}
6 changes: 6 additions & 0 deletions cloudflare/src/framework/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ where
fn body(&self) -> Option<BodyType> {
None
}
fn serialized_body(&self) -> Option<String> {
match self.body() {
Some(body) => Some(serde_json::to_string(&body).unwrap()),
None => None
}
}
fn url(&self, environment: &Environment) -> Url {
Url::from(environment).join(&self.path()).unwrap()
}
Expand Down
4 changes: 2 additions & 2 deletions cloudflare/src/framework/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ impl<'a> ApiClient for HttpApiClient {
)
.query(&endpoint.query());

if let Some(body) = endpoint.body() {
request = request.body(serde_json::to_string(&body).unwrap());
if let Some(body) = endpoint.serialized_body() {
request = request.body(body);
request = request.header(reqwest::header::CONTENT_TYPE, endpoint.content_type());
}

Expand Down