Skip to content

Commit

Permalink
Add support for update remaining and refill (#31)
Browse files Browse the repository at this point in the history
* Support update remaining and refill

* Update readme
  • Loading branch information
Jonxslays authored Dec 31, 2023
1 parent 7a7a2a6 commit 296f8a7
Show file tree
Hide file tree
Showing 7 changed files with 300 additions and 8 deletions.
40 changes: 38 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,16 @@ async fn create_key() {
### Updating a key

```rust
use unkey::models::{UpdateKeyRequest, Wrapped};
use unkey::models::{Refill, RefillInterval, UpdateKeyRequest, Wrapped};
use unkey::Client;

async fn update_key() {
let c = Client::new("unkey_ABC");
let req = UpdateKeyRequest::new("key_XYZ")
.set_name(Some("new_name")) // Update the keys name
.set_ratelimit(None); // Remove any ratelimit on the key
.set_ratelimit(None) // Remove any ratelimit on the key
.set_expires(None) // Remove any expiration date
.set_refill(Some(Refill::new(100, RefillInterval::Daily)));

match c.update_key(req).await {
Wrapped::Ok(res) => println!("{res:?}"),
Expand Down Expand Up @@ -138,6 +140,40 @@ async fn get_api() {
}
```

### Getting key details

```rust
use unkey::models::{GetKeyRequest, Wrapped};
use unkey::Client;

async fn get_key() {
let c = Client::new("unkey_ABC");
let req = GetKeyRequest::new("key_123");

match c.get_key(req).await {
Wrapped::Ok(res) => println!("{res:?}"),
Wrapped::Err(err) => eprintln!("{err:?}"),
}
}
```

### Update remaining verifications

```rust
use unkey::models::{UpdateOp, UpdateRemainingRequest, Wrapped};
use unkey::Client;

async fn update_remaining() {
let c = Client::new("unkey_ABC");
let req = UpdateRemainingRequest::new("key_123", Some(100), UpdateOp::Set);

match c.update_remaining(req).await {
Wrapped::Ok(res) => println!("{res:?}"),
Wrapped::Err(err) => eprintln!("{err:?}"),
}
}
```

## Contributions

Unkey for Rust is open to contributions! Check out the
Expand Down
41 changes: 37 additions & 4 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use crate::models::ListKeysRequest;
use crate::models::ListKeysResponse;
use crate::models::RevokeKeyRequest;
use crate::models::UpdateKeyRequest;
use crate::models::UpdateRemainingRequest;
use crate::models::UpdateRemainingResponse;
use crate::models::VerifyKeyRequest;
use crate::models::VerifyKeyResponse;
use crate::models::Wrapped;
Expand Down Expand Up @@ -274,7 +276,7 @@ impl Client {
/// Retrieves information for the given api id.
///
/// # Arguments
/// - `req`: The get api request to send.
/// - `req`: The get key request to send.
///
/// # Returns
/// A wrapper containing the response, or an [`HttpError`].
Expand All @@ -283,12 +285,12 @@ impl Client {
/// ```no_run
/// # async fn get() {
/// # use unkey::Client;
/// # use unkey::models::UpdateKeyRequest;
/// # use unkey::models::GetKeyRequest;
/// # use unkey::models::Wrapped;
/// let c = Client::new("abc123");
/// let req = UpdateKeyRequest::new("api_id").set_remaining(Some(100));
/// let req = GetKeyRequest::new("api_id");
///
/// match c.update_key(req).await {
/// match c.get_key(req).await {
/// Wrapped::Ok(res) => println!("{:?}", res),
/// Wrapped::Err(err) => println!("{:?}", err),
/// }
Expand All @@ -297,6 +299,37 @@ impl Client {
pub async fn get_key(&self, req: GetKeyRequest) -> Wrapped<ApiKey> {
self.keys.get_key(&self.http, req).await
}

/// Update the remaining verifications for a key.
///
/// # Arguments
/// - `req`: The update remaining request to send.
///
/// # Returns
/// A wrapper containing the response, or an [`HttpError`].
///
/// # Example
/// ```no_run
/// # async fn get() {
/// # use unkey::Client;
/// # use unkey::models::UpdateRemainingRequest;
/// # use unkey::models::UpdateOp;
/// # use unkey::models::Wrapped;
/// let c = Client::new("abc123");
/// let req = UpdateRemainingRequest::new("api_id", Some(100), UpdateOp::Set);
///
/// match c.update_remaining(req).await {
/// Wrapped::Ok(res) => println!("{:?}", res),
/// Wrapped::Err(err) => println!("{:?}", err),
/// }
/// # }
/// ````
pub async fn update_remaining(
&self,
req: UpdateRemainingRequest,
) -> Wrapped<UpdateRemainingResponse> {
self.keys.update_remaining(&self.http, req).await
}
}

#[cfg(test)]
Expand Down
143 changes: 143 additions & 0 deletions src/models/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,23 @@ use serde_json::Value;

use super::Ratelimit;
use super::RatelimitState;
use super::Refill;
use super::UndefinedOr;

/// An update operation that can be performed.
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum UpdateOp {
/// Increment operation.
Increment,

/// Decrement operation.
Decrement,

/// Set operation.
Set,
}

/// An outgoing verify key request.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -72,6 +87,9 @@ pub struct VerifyKeyResponse {

/// The state of the ratelimit set on this key, if any.
pub ratelimit: Option<RatelimitState>,

/// The refill state of this key, if any.
pub refill: Option<Refill>,
}

/// An outgoing create key request.
Expand Down Expand Up @@ -112,6 +130,10 @@ pub struct CreateKeyRequest {
/// The optional ratelimit to set for the key.
#[serde(skip_serializing_if = "UndefinedOr::is_undefined")]
pub ratelimit: UndefinedOr<Ratelimit>,

/// The keys refill state, if any.
#[serde(skip_serializing_if = "UndefinedOr::is_undefined")]
pub refill: UndefinedOr<Refill>,
}

impl CreateKeyRequest {
Expand All @@ -138,6 +160,7 @@ impl CreateKeyRequest {
/// assert_eq!(r.expires, UndefinedOr::Undefined);
/// assert_eq!(r.remaining, UndefinedOr::Undefined);
/// assert_eq!(r.ratelimit, UndefinedOr::Undefined);
/// assert_eq!(r.refill, UndefinedOr::Undefined);
/// ```
#[must_use]
pub fn new<T: Into<String>>(api_id: T) -> Self {
Expand All @@ -151,6 +174,7 @@ impl CreateKeyRequest {
expires: UndefinedOr::Undefined,
remaining: UndefinedOr::Undefined,
ratelimit: UndefinedOr::Undefined,
refill: UndefinedOr::Undefined,
}
}

Expand Down Expand Up @@ -349,6 +373,31 @@ impl CreateKeyRequest {
self.ratelimit = UndefinedOr::Value(ratelimit);
self
}

/// Sets the refill for the new key.
///
/// # Arguments
/// - `refill`: The refill to set.
///
/// # Returns
/// Self for chained calls.
///
/// # Example
/// ```
/// # use unkey::models::CreateKeyRequest;
/// # use unkey::models::Refill;
/// # use unkey::models::RefillInterval;
/// let refill = Refill::new(100, RefillInterval::Daily);
///
/// let r = CreateKeyRequest::new("test").set_refill(refill.clone());
///
/// assert_eq!(r.refill.inner().unwrap(), &refill);
/// ```
#[must_use]
pub fn set_refill(mut self, refill: Refill) -> Self {
self.refill = UndefinedOr::Value(refill);
self
}
}

/// An incoming create key response.
Expand Down Expand Up @@ -397,6 +446,9 @@ pub struct ApiKey {

/// The ratelimit imposed on this key, if any.
pub ratelimit: Option<Ratelimit>,

/// The refill state of this key, if any.
pub refill: Option<Refill>,
}

/// An outgoing revoke key request.
Expand Down Expand Up @@ -470,6 +522,10 @@ pub struct UpdateKeyRequest {
/// The optional new ratelimit to set for the key.
#[serde(skip_serializing_if = "UndefinedOr::is_undefined")]
pub ratelimit: UndefinedOr<Ratelimit>,

/// The optional new refill to set for the key.
#[serde(skip_serializing_if = "UndefinedOr::is_undefined")]
pub refill: UndefinedOr<Refill>,
}

impl UpdateKeyRequest {
Expand All @@ -494,6 +550,7 @@ impl UpdateKeyRequest {
/// assert_eq!(r.expires, UndefinedOr::Undefined);
/// assert_eq!(r.remaining, UndefinedOr::Undefined);
/// assert_eq!(r.ratelimit, UndefinedOr::Undefined);
/// assert_eq!(r.refill, UndefinedOr::Undefined);
/// ```
#[must_use]
pub fn new<T: Into<String>>(key_id: T) -> Self {
Expand Down Expand Up @@ -722,6 +779,43 @@ impl UpdateKeyRequest {
self.ratelimit = ratelimit.into();
self
}

/// Sets or unsets the refill for the key.
///
/// # Arguments
/// - `refill`: The refill to set or unset.
///
/// # Returns
/// Self for chained calls.
///
/// # Example
/// ```
/// # use unkey::models::UpdateKeyRequest;
/// # use unkey::models::Refill;
/// # use unkey::models::RefillInterval;
/// # use unkey::models::UndefinedOr;
/// let r = UpdateKeyRequest::new("test");
///
/// assert_eq!(r.ratelimit, UndefinedOr::Undefined);
/// assert_eq!(r.ratelimit.inner(), None);
///
/// let refill = Refill::new(100, RefillInterval::Daily);
///
/// let r = r.set_refill(Some(refill.clone()));
///
/// assert_eq!(r.refill, UndefinedOr::Value(refill.clone()));
/// assert_eq!(r.refill.inner(), Some(&refill));
///
/// let r = r.set_refill(None);
///
/// assert_eq!(r.refill, UndefinedOr::Null);
/// assert_eq!(r.refill.inner(), None);
/// ```
#[must_use]
pub fn set_refill(mut self, refill: Option<Refill>) -> Self {
self.refill = refill.into();
self
}
}

/// An outgoing get key request.
Expand Down Expand Up @@ -754,3 +848,52 @@ impl GetKeyRequest {
Self { key_id: key_id.into() }
}
}

/// An outgoing update remaining request.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateRemainingRequest {
/// The unique id of the key to updating remaining for.
pub key_id: String,

/// The value to perform the operation on.
pub value: Option<usize>,

/// The update operation to perform.
pub op: UpdateOp,
}

impl UpdateRemainingRequest {
/// Creates a new update remaining request.
///
/// # Arguments
/// - `key_id`: The id of the key to update remaining for.
/// - `value`: The value to perform the operation on.
/// - `op`: The update operation to perform.
///
/// # Returns
/// The update remaining request.
///
/// # Example
/// ```
/// # use unkey::models::UpdateRemainingRequest;
/// # use unkey::models::UpdateOp;
/// let r = UpdateRemainingRequest::new("test_ABC123", Some(100), UpdateOp::Set);
///
/// assert_eq!(r.key_id, String::from("test_ABC123"));
/// assert_eq!(r.value.unwrap(), 100);
/// assert_eq!(r.op, UpdateOp::Set);
/// ```
#[must_use]
#[rustfmt::skip]
pub fn new<T: Into<String>>(key_id: T, value: Option<usize>, op: UpdateOp) -> Self {
Self { key_id: key_id.into(), value, op }
}
}

/// An outgoing update remaining request.
#[derive(Debug, Clone, Deserialize)]
pub struct UpdateRemainingResponse {
/// The number of remaining verifications for the key.
pub remaining: usize,
}
2 changes: 2 additions & 0 deletions src/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ mod apis;
mod http;
mod keys;
mod ratelimit;
mod refill;
mod undefined;

pub use apis::*;
pub use http::*;
pub use keys::*;
pub use ratelimit::*;
pub use refill::*;
pub use undefined::*;
Loading

0 comments on commit 296f8a7

Please sign in to comment.