BlockPalettesClient

Struct BlockPalettesClient 

Source
pub struct BlockPalettesClient<'a> { /* private fields */ }
Expand description

An asynchronous client for the Block Palettes API.

This struct provides methods to interact with various endpoints of the Block Palettes API, allowing you to search for palettes, retrieve block information, and get palette details.

§Examples

use blockpalettes_client::{BlockPalettesClient, SortOrder};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = BlockPalettesClient::new(reqwest::Client::new());
    let popular_blocks = client.popular_blocks().await?;
    println!("First popular block: {}", popular_blocks[0].name);
    Ok(())
}

Implementations§

Source§

impl<'a> BlockPalettesClient<'a>

Source

pub const fn new(client: Client) -> Self

Creates a new BlockPalettesClient instance.

§Arguments
  • client - An instance of reqwest::Client to use for making HTTP requests.
§Returns

A new BlockPalettesClient configured to use the provided reqwest::Client and the default base URL (https://www.blockpalettes.com).

§Examples
use blockpalettes_client::BlockPalettesClient;

let reqwest_client = reqwest::Client::new();
let bp_client = BlockPalettesClient::new(reqwest_client);
Source

pub async fn search_blocks(&self, query: impl AsRef<str>) -> Result<Vec<String>>

Searches for blocks that match a given query string.

This method queries the /api/palettes/search-block.php endpoint.

§Arguments
  • query - The search string for blocks (e.g., “stone”, “wood”).
§Returns

A Result containing a Vec<String> of block names if successful, or a BlockPalettesError if the request fails or the API returns an error.

§Examples
use blockpalettes_client::BlockPalettesClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = BlockPalettesClient::new(reqwest::Client::new());
    let blocks = client.search_blocks("dirt").await?;
    println!("Found blocks: {:?}", blocks);
    Ok(())
}
Source

pub async fn popular_blocks(&self) -> Result<Vec<PopularBlock>>

Retrieves a list of popular blocks.

This method queries the /api/palettes/popular-blocks.php endpoint.

§Returns

A Result containing a Vec<PopularBlock> if successful, or a BlockPalettesError if the request fails or the API returns an error.

§Examples
use blockpalettes_client::BlockPalettesClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = BlockPalettesClient::new(reqwest::Client::new());
    let popular_blocks = client.popular_blocks().await?;
    for block in popular_blocks.iter().take(3) {
        println!("Block: {}, Count: {}", block.name, block.count);
    }
    Ok(())
}
Source

pub async fn get_palettes( &self, blocks: &[&str], sort: SortOrder, page: u32, limit: u32, ) -> Result<PaletteResponse>

Retrieves a list of palettes based on specified blocks, sorting order, pagination, and limit.

This method queries the /api/palettes/all_palettes.php endpoint. It internally filters the results to ensure all specified blocks are present in the returned palettes.

§Arguments
  • blocks - A slice of string references representing the blocks that must be present in the palettes.
  • sort - The desired sorting order for the palettes (e.g., SortOrder::Recent).
  • page - The page number of the results to retrieve (1-indexed).
  • limit - The maximum number of palettes to return per page.
§Returns

A Result containing a PaletteResponse if successful, or a BlockPalettesError if the request fails or the API returns an error.

§Examples
use blockpalettes_client::{BlockPalettesClient, SortOrder};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = BlockPalettesClient::new(reqwest::Client::new());
    let blocks_to_search = &["oak_log", "dirt"];
    let response = client
        .get_palettes(blocks_to_search, SortOrder::Popular, 1, 5)
        .await?;

    if let Some(palettes) = response.palettes {
        println!("Found {} popular palettes containing oak_log and dirt:", palettes.len());
        for palette in palettes {
            println!("- ID: {}, Name: {:?}", palette.id, palette.name());
        }
    }
    Ok(())
}
Source

pub async fn get_palette_details(&self, id: u64) -> Result<PaletteDetails>

Retrieves detailed information for a single palette by its ID.

This method queries the /api/palettes/single_palette.php endpoint.

§Arguments
  • id - The unique identifier of the palette.
§Returns

A Result containing a PaletteDetails if successful, or a BlockPalettesError if the request fails, the API returns an error (e.g., palette not found), or the response cannot be deserialized.

§Examples
use blockpalettes_client::BlockPalettesClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = BlockPalettesClient::new(reqwest::Client::new());
    let palette_id = 12345; // Replace with an actual palette ID
    match client.get_palette_details(palette_id).await {
        Ok(details) => println!("Palette ID {}: Username {}", details.id, details.username),
        Err(e) => eprintln!("Failed to get palette details: {}", e),
    }
    Ok(())
}
Source

pub async fn get_similar_palettes( &self, palette_id: u64, ) -> Result<Vec<Palette>>

Retrieves a list of palettes similar to a given palette ID.

This method queries the /api/palettes/similar_palettes.php endpoint.

§Arguments
  • palette_id - The ID of the reference palette to find similar ones.
§Returns

A Result containing a Vec<Palette> of similar palettes if successful, or a BlockPalettesError if the request fails, the API returns an error, or the response cannot be deserialized.

§Examples
use blockpalettes_client::BlockPalettesClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = BlockPalettesClient::new(reqwest::Client::new());
    let reference_palette_id = 56655; // Replace with an actual palette ID
    let similar_palettes = client.get_similar_palettes(reference_palette_id).await?;
    println!("Found {} similar palettes for ID {}:", similar_palettes.len(), reference_palette_id);
    for palette in similar_palettes.iter().take(3) {
        println!("- ID: {}, Name: {:?}", palette.id, palette.name());
    }
    Ok(())
}
Source

pub async fn scrape_palette_page( &self, palette_id: u64, ) -> Result<PalettePageDetails>

Scrapes details directly from a Block Palettes HTML page for a given palette ID.

This method is useful for extracting information that might not be available directly through the public API endpoints, such as the full list of blocks displayed on the page or IDs of similar palettes linked on the page.

§Arguments
  • palette_id - The ID of the palette whose page details are to be scraped.
§Returns

A Result containing a PalettePageDetails if successful, or a BlockPalettesError if the request fails, HTML parsing fails, or expected elements are not found.

§Caveats

This method relies on the specific HTML structure of blockpalettes.com. Any changes to the website’s front-end might break this scraping functionality.

§Examples
use blockpalettes_client::BlockPalettesClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = BlockPalettesClient::new(reqwest::Client::new());
    let palette_id = 12345; // Replace with an actual palette ID
    match client.scrape_palette_page(palette_id).await {
        Ok(details) => {
            println!("Scraped blocks for palette {}: {:?}", palette_id, details.blocks);
            println!("Similar palette IDs: {:?}", details.similar_palette_ids);
        },
        Err(e) => eprintln!("Failed to scrape palette page: {}", e),
    }
    Ok(())
}

Trait Implementations§

Source§

impl<'a> Clone for BlockPalettesClient<'a>

Source§

fn clone(&self) -> BlockPalettesClient<'a>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Debug for BlockPalettesClient<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,