Skip to content

Commit

Permalink
Merge pull request #20 from cloudflare/sssilver/17
Browse files Browse the repository at this point in the history
fix #17: Adhere to Rust naming conventions
  • Loading branch information
adamchalmers authored Aug 13, 2019
2 parents f577372 + d47a9b1 commit 2685244
Show file tree
Hide file tree
Showing 12 changed files with 128 additions and 128 deletions.
46 changes: 23 additions & 23 deletions example/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,27 @@ extern crate clap;
extern crate cloudflare;

use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use cloudflare::apiclient::APIClient;
use cloudflare::apiclient::ApiClient;
use cloudflare::auth::Credentials;
use cloudflare::dns;
use cloudflare::mock::{MockAPIClient, NoopEndpoint};
use cloudflare::response::{APIFailure, APIResponse, APIResult};
use cloudflare::mock::{MockApiClient, NoopEndpoint};
use cloudflare::response::{ApiFailure, ApiResponse, ApiResult};
use cloudflare::zone;
use cloudflare::{HTTPAPIClient, OrderDirection};
use cloudflare::{HttpApiClient, OrderDirection};

type SectionFunction<APIClientType> = fn(&ArgMatches, &APIClientType);
type SectionFunction<ApiClientType> = fn(&ArgMatches, &ApiClientType);

struct Section<'a, APIClientType: APIClient> {
struct Section<'a, ApiClientType: ApiClient> {
args: Vec<Arg<'a, 'a>>,
description: &'a str,
function: SectionFunction<APIClientType>,
function: SectionFunction<ApiClientType>,
}

fn print_response<T: APIResult>(response: APIResponse<T>) {
fn print_response<T: ApiResult>(response: ApiResponse<T>) {
match response {
Ok(success) => println!("Success: {:#?}", success),
Err(e) => match e {
APIFailure::Error(status, errors) => {
ApiFailure::Error(status, errors) => {
println!("HTTP {}:", status);
for err in errors.errors {
println!("Error {}: {}", err.code, err.message);
Expand All @@ -36,24 +36,24 @@ fn print_response<T: APIResult>(response: APIResponse<T>) {
println!("{}: {}", k, v);
}
}
APIFailure::Invalid(reqwest_err) => println!("Error: {}", reqwest_err),
ApiFailure::Invalid(reqwest_err) => println!("Error: {}", reqwest_err),
},
}
}

fn zone<APIClientType: APIClient>(arg_matches: &ArgMatches, api_client: &APIClientType) {
fn zone<ApiClientType: ApiClient>(arg_matches: &ArgMatches, api_client: &ApiClientType) {
let zone_identifier = arg_matches.value_of("zone_identifier").unwrap();
let response = api_client.request(&zone::ZoneDetails {
identifier: zone_identifier,
});
print_response(response)
}

fn dns<APIClientType: APIClient>(arg_matches: &ArgMatches, api_client: &APIClientType) {
fn dns<ApiClientType: ApiClient>(arg_matches: &ArgMatches, api_client: &ApiClientType) {
let zone_identifier = arg_matches.value_of("zone_identifier").unwrap();
let response = api_client.request(&dns::ListDNSRecords {
let response = api_client.request(&dns::ListDnsRecords {
zone_identifier,
params: dns::ListDNSRecordsParams {
params: dns::ListDnsRecordsParams {
direction: Some(OrderDirection::Ascending),
..Default::default()
},
Expand All @@ -62,9 +62,9 @@ fn dns<APIClientType: APIClient>(arg_matches: &ArgMatches, api_client: &APIClien
print_response(response);
}

fn create_txt_record<APIClientType: APIClient>(
fn create_txt_record<ApiClientType: ApiClient>(
arg_matches: &ArgMatches,
api_client: &APIClientType,
api_client: &ApiClientType,
) {
let usage = "usage: create_txt_record ZONE_ID NAME CONTENT";

Expand All @@ -79,11 +79,11 @@ fn create_txt_record<APIClientType: APIClient>(
let content_missing = format!("missing '{}': {}", "CONTENT", usage);
let content = arg_matches.value_of("content").expect(&content_missing);

let response = api_client.request(&dns::CreateDNSRecord {
let response = api_client.request(&dns::CreateDnsRecord {
zone_identifier,
params: dns::CreateDNSRecordParams {
params: dns::CreateDnsRecordParams {
name,
content: dns::DNSContent::TXT {
content: dns::DnsContent::TXT {
content: content.to_owned(),
},
priority: None,
Expand All @@ -95,8 +95,8 @@ fn create_txt_record<APIClientType: APIClient>(
print_response(response);
}

fn mock_api<APIClientType: APIClient>(_args: &ArgMatches, _api: &APIClientType) {
let mock_api = MockAPIClient {};
fn mock_api<ApiClientType: ApiClient>(_args: &ArgMatches, _api: &ApiClientType) {
let mock_api = MockApiClient {};
let endpoint = NoopEndpoint {};
let _ = mock_api.request(&endpoint);
println!("Ran mock API")
Expand Down Expand Up @@ -160,14 +160,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let matched_sections =
sections
.iter()
.filter(|&(section_name, _): &(&&str, &Section<HTTPAPIClient>)| {
.filter(|&(section_name, _): &(&&str, &Section<HttpApiClient>)| {
matches.subcommand_matches(section_name).is_some()
});

let key = matches.value_of("auth-key").unwrap();
let email = matches.value_of("email").unwrap();

let api_client = HTTPAPIClient::new(Credentials::User {
let api_client = HttpApiClient::new(Credentials::User {
key: key.to_string(),
email: email.to_string(),
});
Expand Down
8 changes: 4 additions & 4 deletions src/apiclient.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use crate::endpoint::Endpoint;
use crate::response::{APIResponse, APIResult};
use crate::response::{ApiResponse, ApiResult};
use serde::Serialize;

pub trait APIClient {
pub trait ApiClient {
fn request<ResultType, QueryType, BodyType>(
&self,
endpoint: &dyn Endpoint<ResultType, QueryType, BodyType>,
) -> APIResponse<ResultType>
) -> ApiResponse<ResultType>
where
ResultType: APIResult,
ResultType: ApiResult,
QueryType: Serialize,
BodyType: Serialize;
}
50 changes: 25 additions & 25 deletions src/dns.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,50 @@
/// https://api.cloudflare.com/#dns-records-for-a-zone-properties
use super::{OrderDirection, SearchMatch};
use crate::endpoint::{Endpoint, Method};
use crate::response::APIResult;
use crate::response::ApiResult;
use chrono::offset::Utc;
use chrono::DateTime;
use std::net::{Ipv4Addr, Ipv6Addr};

/// List DNS Records
/// https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
pub struct ListDNSRecords<'a> {
pub struct ListDnsRecords<'a> {
pub zone_identifier: &'a str,
pub params: ListDNSRecordsParams,
pub params: ListDnsRecordsParams,
}
impl<'a> Endpoint<Vec<DNSRecord>, ListDNSRecordsParams> for ListDNSRecords<'a> {
impl<'a> Endpoint<Vec<DnsRecord>, ListDnsRecordsParams> for ListDnsRecords<'a> {
fn method(&self) -> Method {
Method::Get
}
fn path(&self) -> String {
format!("zones/{}/dns_records", self.zone_identifier)
}
fn query(&self) -> Option<ListDNSRecordsParams> {
fn query(&self) -> Option<ListDnsRecordsParams> {
Some(self.params.clone())
}
}

/// Create DNS Record
/// https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record
pub struct CreateDNSRecord<'a> {
pub struct CreateDnsRecord<'a> {
pub zone_identifier: &'a str,
pub params: CreateDNSRecordParams<'a>,
pub params: CreateDnsRecordParams<'a>,
}

impl<'a> Endpoint<DNSRecord, (), CreateDNSRecordParams<'a>> for CreateDNSRecord<'a> {
impl<'a> Endpoint<DnsRecord, (), CreateDnsRecordParams<'a>> for CreateDnsRecord<'a> {
fn method(&self) -> Method {
Method::Post
}
fn path(&self) -> String {
format!("zones/{}/dns_records", self.zone_identifier)
}
fn body(&self) -> Option<CreateDNSRecordParams<'a>> {
fn body(&self) -> Option<CreateDnsRecordParams<'a>> {
Some(self.params.clone())
}
}

#[derive(Serialize, Clone, Debug)]
pub struct CreateDNSRecordParams<'a> {
pub struct CreateDnsRecordParams<'a> {
/// Time to live for DNS record. Value of 1 is 'automatic'
#[serde(skip_serializing_if = "Option::is_none")]
pub ttl: Option<u32>,
Expand All @@ -59,16 +59,16 @@ pub struct CreateDNSRecordParams<'a> {
pub name: &'a str,
/// Type of the DNS record that also holds the record value
#[serde(flatten)]
pub content: DNSContent,
pub content: DnsContent,
}

/// Delete DNS Record
/// https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record
pub struct DeleteDNSRecord<'a> {
pub struct DeleteDnsRecord<'a> {
pub zone_identifier: &'a str,
pub identifier: &'a str,
}
impl<'a> Endpoint<DeleteDNSRecordResponse> for DeleteDNSRecord<'a> {
impl<'a> Endpoint<DeleteDnsRecordResponse> for DeleteDnsRecord<'a> {
fn method(&self) -> Method {
Method::Delete
}
Expand All @@ -82,26 +82,26 @@ impl<'a> Endpoint<DeleteDNSRecordResponse> for DeleteDNSRecord<'a> {

#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "lowercase")]
pub enum ListDNSRecordsOrder {
pub enum ListDnsRecordsOrder {
Type,
Name,
Content,
TTL,
Ttl,
Proxied,
}

#[derive(Serialize, Clone, Debug, Default)]
pub struct ListDNSRecordsParams {
pub struct ListDnsRecordsParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub record_type: Option<DNSContent>,
pub record_type: Option<DnsContent>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub per_page: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub order: Option<ListDNSRecordsOrder>,
pub order: Option<ListDnsRecordsOrder>,
#[serde(skip_serializing_if = "Option::is_none")]
pub direction: Option<OrderDirection>,
#[serde(rename = "match", skip_serializing_if = "Option::is_none")]
Expand All @@ -120,7 +120,7 @@ pub struct Meta {
/// here as an associated, strongly typed value.
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "type")]
pub enum DNSContent {
pub enum DnsContent {
A { content: Ipv4Addr },
AAAA { content: Ipv6Addr },
CNAME { content: String },
Expand All @@ -130,13 +130,13 @@ pub enum DNSContent {
}

#[derive(Deserialize, Debug)]
pub struct DeleteDNSRecordResponse {
pub struct DeleteDnsRecordResponse {
/// DNS record identifier tag
pub id: String,
}

#[derive(Deserialize, Debug)]
pub struct DNSRecord {
pub struct DnsRecord {
/// Extra Cloudflare-specific information about the record
pub meta: Meta,
/// Whether this record can be modified/deleted (true means it's managed by Cloudflare)
Expand All @@ -155,7 +155,7 @@ pub struct DNSRecord {
pub proxiable: bool,
/// Type of the DNS record that also holds the record value
#[serde(flatten)]
pub content: DNSContent,
pub content: DnsContent,
/// DNS record identifier tag
pub id: String,
/// Whether the record is receiving the performance and security benefits of Cloudflare
Expand All @@ -164,6 +164,6 @@ pub struct DNSRecord {
pub zone_name: String,
}

impl APIResult for DNSRecord {}
impl APIResult for Vec<DNSRecord> {}
impl APIResult for DeleteDNSRecordResponse {}
impl ApiResult for DnsRecord {}
impl ApiResult for Vec<DnsRecord> {}
impl ApiResult for DeleteDnsRecordResponse {}
4 changes: 2 additions & 2 deletions src/endpoint.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::Environment;
use crate::response::APIResult;
use crate::response::ApiResult;
use serde::Serialize;
use url::Url;

Expand All @@ -13,7 +13,7 @@ pub enum Method {

pub trait Endpoint<ResultType = (), QueryType = (), BodyType = ()>
where
ResultType: APIResult,
ResultType: ApiResult,
QueryType: Serialize,
BodyType: Serialize,
{
Expand Down
20 changes: 10 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ pub mod response;
pub mod workerskv;
pub mod zone;

use crate::apiclient::APIClient;
use crate::apiclient::ApiClient;
use crate::auth::{AuthClient, Credentials};
use crate::endpoint::{Endpoint, Method};
use crate::response::{APIResponse, APIResult};
use crate::response::{ApiResponse, ApiResult};
use serde::Serialize;

#[derive(Serialize, Clone, Debug)]
Expand Down Expand Up @@ -54,15 +54,15 @@ impl<'a> From<&'a Environment> for url::Url {
}
}

pub struct HTTPAPIClient {
pub struct HttpApiClient {
environment: Environment,
credentials: Credentials,
http_client: reqwest::Client,
}

impl HTTPAPIClient {
pub fn new(credentials: Credentials) -> HTTPAPIClient {
HTTPAPIClient {
impl HttpApiClient {
pub fn new(credentials: Credentials) -> HttpApiClient {
HttpApiClient {
environment: Environment::Production,
credentials,
http_client: reqwest::Client::new(),
Expand All @@ -71,14 +71,14 @@ impl HTTPAPIClient {
}

// TODO: This should probably just implement request for the Reqwest client itself :)
// TODO: It should also probably be called `ReqwestAPIClient` rather than `HTTPAPIClient`.
impl<'a> APIClient for HTTPAPIClient {
// TODO: It should also probably be called `ReqwestApiClient` rather than `HttpApiClient`.
impl<'a> ApiClient for HttpApiClient {
fn request<ResultType, QueryType, BodyType>(
&self,
endpoint: &dyn Endpoint<ResultType, QueryType, BodyType>,
) -> APIResponse<ResultType>
) -> ApiResponse<ResultType>
where
ResultType: APIResult,
ResultType: ApiResult,
QueryType: Serialize,
BodyType: Serialize,
{
Expand Down
Loading

0 comments on commit 2685244

Please sign in to comment.