Struct ParseCloud

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

Provides methods for interacting with Parse Cloud Code functions.

An instance of ParseCloud is obtained by calling the cloud() method on a Parse instance. It allows for executing server-side Cloud Code functions, passing parameters, and receiving their results.

Cloud Code functions are custom JavaScript (or other supported language) functions deployed to your Parse Server, enabling server-side logic, data validation, triggers, and more, without exposing sensitive operations or master key usage directly to the client.

This handle operates in the context of the Parse it was created from, using its configuration (server URL, app ID, keys, and current session token if any) for API requests to the /functions endpoint.

Implementations§

Source§

impl<'a> ParseCloud<'a>

Source

pub async fn run<P, R>( &self, function_name: &str, params: &P, ) -> Result<R, ParseError>
where P: Serialize + Send + Sync, R: DeserializeOwned + Send + Sync + 'static,

Runs a Parse Cloud Function and returns its result.

This method sends a POST request to the /functions/:functionName endpoint, where :functionName is the name of the Cloud Code function to execute. The params argument is serialized to JSON and sent as the request body.

The Parse Server executes the specified function and is expected to return a JSON object of the form {"result": ...}, where ... is the actual value returned by the function. This method automatically unwraps the result field and deserializes its content into the type R specified by the caller.

§Type Parameters
  • P: The type of the params argument. This type must implement Serialize, Send, and Sync. It can be any serializable type, such as a custom struct, serde_json::Value, or a HashMap.
  • R: The expected type of the result field from the cloud function’s response. This type must implement DeserializeOwned, Send, Sync, and be 'static.
§Arguments
  • function_name: A string slice representing the name of the cloud function to execute.
  • params: A reference to the parameters to pass to the cloud function.
§Returns

A Result containing the deserialized value from the result field of the cloud function’s response if successful. Returns a ParseError if the function name is invalid, parameters cannot be serialized, the server returns an error (e.g., function not found, internal error in cloud code), the response cannot be deserialized into R, or any other network/request error occurs.

§Examples
use parse_rs::{Parse, ParseError};
use serde::{Serialize, Deserialize};
use serde_json::json; // For ad-hoc JSON parameters

// Define a struct for expected parameters if your function takes structured input
#[derive(Serialize)]
struct HelloParams<'a> {
    name: &'a str,
}

// Define a struct for the expected result if your function returns structured data
#[derive(Deserialize, Debug)]
struct HelloResponse {
    message: String,
    timestamp: u64,
}


// Example 1: Calling a cloud function named "hello" with simple JSON parameters
// and expecting a simple string response.
// Assume cloud function "hello" is defined as: Parse.Cloud.define("hello", req => `Hello, ${req.params.name}!`);
let params1 = json!({ "name": "World" });
match client.cloud().run::<_, String>("hello", &params1).await {
    Ok(response_message) => {
        println!("Cloud function 'hello' responded: {}", response_message);
        assert_eq!(response_message, "Hello, World!");
    }
    Err(e) => eprintln!("Failed to run cloud function 'hello': {}", e),
}

// Example 2: Calling a cloud function "complexHello" with structured parameters
// and expecting a structured response.
// Assume cloud function "complexHello" is defined as:
// Parse.Cloud.define("complexHello", req => {
//   return { message: `Complex hello to ${req.params.name}!`, timestamp: Date.now() };
// });
let params2 = HelloParams { name: "SDK User" };
match client.cloud().run::<HelloParams, HelloResponse>("complexHello", &params2).await {
    Ok(response_data) => {
        println!(
            "Cloud function 'complexHello' responded with message: '{}' at {}",
            response_data.message,
            response_data.timestamp
        );
        assert!(response_data.message.contains("SDK User"));
    }
    Err(e) => eprintln!("Failed to run cloud function 'complexHello': {}", e),
}

// Example 3: Calling a cloud function that takes no parameters and returns a number
// Assume cloud function "randomNumber" is defined as: Parse.Cloud.define("randomNumber", () => Math.random() * 100);
let empty_params = json!({}); // Or use a unit type `()` if your function truly takes no params and server handles it.
match client.cloud().run::<_, f64>("randomNumber", &empty_params).await {
    Ok(number) => {
        println!("Cloud function 'randomNumber' responded: {}", number);
        assert!(number >= 0.0 && number <= 100.0);
    }
    Err(e) => eprintln!("Failed to run cloud function 'randomNumber': {}", e),
}

Trait Implementations§

Source§

impl<'a> Debug for ParseCloud<'a>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for ParseCloud<'a>

§

impl<'a> !RefUnwindSafe for ParseCloud<'a>

§

impl<'a> Send for ParseCloud<'a>

§

impl<'a> Sync for ParseCloud<'a>

§

impl<'a> Unpin for ParseCloud<'a>

§

impl<'a> !UnwindSafe for ParseCloud<'a>

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> 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, 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,