Skip to content
Merged
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
6 changes: 5 additions & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,5 +70,9 @@ jobs:
- name: Run REST API Integration Tests
run: |
cargo test --test rest_api_integration_test


- name: Destroy Scratch Org
if: always() # This step runs even if 'Run Tests' failed
run: |
sf org delete scratch --target-org SCRATCH --no-prompt

7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@ chrono = { version = "0.4.45", features = ["serde"] }
mockito = "1.7.2"
tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros"] }
#env_logger = "0.11.3"
#anyhow = "1.0.32"
anyhow = "1.0.32"
html-escape = "0.2.15"
2 changes: 1 addition & 1 deletion src/primary_types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ pub trait SObject {
fn set_id(&mut self, id: Option<&str>) -> &mut Self;

fn set_owner_id(&mut self, id: Option<&str>) -> &mut Self;

fn get_owner_id(&self) -> Option<&str>;
}
54 changes: 40 additions & 14 deletions src/rest_api/sobjects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
//! # See
//! <https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_basic_info.htm>

use std::collections::HashMap;
use super::{RestApi, handle_empty_response, handle_json_response};
use crate::Error;
use crate::rest_api::responses::create_response::CreateResponse;
Expand All @@ -32,9 +33,12 @@ use crate::rest_api::responses::describe_sobject_result::DescribeSObjectResult;
use crate::rest_api::responses::sobject_info::SObjectInfo;
use crate::rest_api::responses::updated_sobjects_response::UpdatedSObjectsResponse;
use reqwest::Response;
use serde::Serialize;
use serde::{Serialize};
use serde::de::DeserializeOwned;
use std::fmt::Debug;
use serde_json::Value;
use crate::primary_types::SObject;
use crate::rest_api::responses::sobject_attribute::SObjectAttribute;

impl RestApi {
/// Creates a single new record in a Salesforce with the provided values.
Expand All @@ -47,8 +51,8 @@ impl RestApi {
/// - `params`: An instance of type `T` containing the details of the record to be created.
///
/// # Returns
/// - `Result<CreateResponse, Error>`:
/// - On success, returns a `CreateResponse` containing information about the created record, such as its ID.
/// - `Result<T, Error>`:
/// - On success, returns the updated instance of type 'T' containing the Salesforce record id.
/// - On failure, returns an `Error` detailing what went wrong during the request.
///
/// # Errors
Expand All @@ -73,8 +77,8 @@ impl RestApi {
/// let mut account = Account::new();
/// account.name = Some("Example Account".to_string());
///
/// match api.create_sobject("Account", account).await {
/// Ok(response) => println!("Record ID: {}", response.id),
/// match api.create_sobject(account).await {
/// Ok(record) => println!("Record ID: {:?}", record.id()),
/// Err(error) => println!("Error creating account: {:?}", error),
/// }
/// Ok(())
Expand All @@ -90,18 +94,28 @@ impl RestApi {
///
/// # See
/// <https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_basic_info_post.htm>
pub async fn create_sobject<T: Serialize + Debug>(
pub async fn create_sobject<T: Serialize + Debug + SObject + Clone>(
&mut self,
object_name: &str,
params: T,
) -> Result<CreateResponse, Error> {
mut record: T,
) -> Result<T, Error> {

// Set the owner_id attribute to the authenticated user's ID if its None
if record.get_owner_id().is_none() {
record.set_owner_id(self.client.get_user_id().as_deref().map(str::to_string).as_deref());
}

let resource_url = format!(
"{}/sobjects/{}",
self.client.base_version_path()?,
object_name
record.get_sobject_type()
);
let response = self.client.post(resource_url, params, vec![]).await?;
handle_json_response(response).await
let response = self.client.post(resource_url, record.clone(), vec![]).await?;
let response: CreateResponse = handle_json_response(response).await?;
if response.success {
record.set_id(Some(&response.id));
}
// Fixme - should we throw an error if the response is not success?
Ok(record)
}

/// Get Object Metadata Using sObject Basic Information
Expand Down Expand Up @@ -489,7 +503,10 @@ impl RestApi {
/// This function depends on the client's `base_path()` method to obtain the base URL and the
/// `get` method to perform the HTTP GET request. The response is then handled by the
/// `handle_json_response` utility.
pub async fn fetch_by_id<T: DeserializeOwned>(
///
/// # See
/// <https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_retrieve_get.htm>
pub async fn fetch_by_id<T: DeserializeOwned>( // fixme rename into sobject_by_id
&mut self,
sobject_name: &str,
id: &str,
Expand All @@ -501,7 +518,16 @@ impl RestApi {
id
);
let response = self.client.get(resource_url, vec![], vec![]).await?;
handle_json_response(response).await

// Adds the Attribute attribute to the response
let mut attr = SObjectAttribute::new(sobject_name);
attr.set_id(Some(id));
let json = serde_json::to_value(attr).map_err(Error::from)?;

let mut hm: HashMap<String, Value> = handle_json_response(response).await?;
hm.insert("attributes".to_string(), json);
let json = serde_json::to_value(hm).map_err(Error::from)?;
serde_json::from_value(json).map_err(Error::from)
}

/// sObject Get Deleted
Expand Down
35 changes: 21 additions & 14 deletions src/rest_api/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ use mockito::Server;
use crate::client::client::{Client};
use crate::errors::Error;
use super::*;
use serde::{Deserialize, Serialize};

use crate as rustsf;
use serde_json::json;
use crate::DefSObject;
use crate::rest_api::responses::query_response::QueryResponse;
use crate::primary_types::SObject;

fn create_test_rest_api(server_url: &str) -> RestApi {
let mut client = Client::new();
Expand Down Expand Up @@ -50,11 +52,17 @@ async fn test_base_path_not_logged_in() {
}
}

#[derive(Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
struct Account {
id: String,
name: String,
#[DefSObject(sobject_type = "Account", fields="name")]
struct Account { }

impl Account {
pub fn get_name(&self) -> Option<&str> {
self.name.as_ref().map(|s| s.as_str())
}
pub fn set_name(mut self, name: String) -> Self {
self.name = Some(name);
self
}
}

#[tokio::test]
Expand Down Expand Up @@ -212,9 +220,9 @@ async fn test_find_by_id() {
.await;

let mut api = create_test_rest_api(&server.url());
let res = api.fetch_by_id::<Account>("Account", "001xx000003DGbX").await.unwrap();
assert_eq!(res.id, "001xx000003DGbX");
assert_eq!(res.name, "Acme");
let account = api.fetch_by_id::<Account>("Account", "001xx000003DGbX").await.unwrap();
assert_eq!(account.id(), Some("001xx000003DGbX"));
assert_eq!(account.get_name(), Some("Acme"));
mock.assert_async().await;
}

Expand All @@ -230,11 +238,10 @@ async fn test_create() {
.await;

let mut api = create_test_rest_api(&server.url());
let mut params = std::collections::HashMap::new();
params.insert("Name", "Test Account");
let res = api.create_sobject("Account", params).await.unwrap();
assert_eq!(res.id, "001xx000003DGbX");
assert_eq!(res.success, true);
let mut account = Account::new().set_name("Test Account".to_string());

let account = api.create_sobject(account).await.unwrap();
assert_eq!(account.id(), Some("001xx000003DGbX"));
mock.assert_async().await;
}

Expand Down
25 changes: 25 additions & 0 deletions tests/common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use rustsf::{Client, RestApi, DefSObject};
use std::env;
use anyhow::Result;

pub async fn get_rest_api_client() -> Result<RestApi> {
let mut client = Client::new();
client.login_with_sfdx_auth_url(&env::var("SCRATCH_AUTH_URL").expect("SCRATCH_AUTH_URL not set")).await?;
Ok(RestApi::new(client))
}

#[DefSObject(sobject_type = "Account", fields="name")]
pub struct Account {

}

impl Account {
pub fn set_name(mut self, name: String) -> Self {
self.name = Some(name);
self
}

pub fn get_name(&self) -> Option<&str> {
self.name.as_deref()
}
}
52 changes: 52 additions & 0 deletions tests/rest_api_integration_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
extern crate rustsf;
use anyhow::Result;
use crate::rustsf::primary_types::SObject;

mod common;


/// Check the available API versions
#[tokio::test]
async fn check_versions() -> Result<()> {
let mut client = common::get_rest_api_client().await?;
let versions = client.api_versions().await?;

assert_ne!(0, versions.len());
assert_eq!("67.0", versions[versions.len()-1].version); // this forces us to always use the latest version
Ok(())
}

/// Create an Account record and Fetch it via Id
#[tokio::test]
async fn create_fetch_delete_sobject() -> Result<()> {
let mut client = common::get_rest_api_client().await?;

// Create an Account record
let account = client.create_sobject(common::Account::new()
.set_name("Test Account".to_string())).await?;
assert!(account.id().is_some());
assert_eq!(18, account.id().unwrap().len()); // We got a 18 character Salesforce Id

// Fetch the Account record
let account = client.fetch_by_id::<common::Account>("Account", &account.id().unwrap()).await?;
assert_eq!("Test Account", account.get_name().unwrap());

client.delete_sobject("Account", &account.id().unwrap()).await?;

match client.fetch_by_id::<common::Account>("Account", &account.id().unwrap()).await {
Ok(_) => panic!("Account record should have been deleted"),
Err(_) => (), // fixme assert the right error message
};

Ok(())
}
/*
/// Fetch the Account record via SOQL


/// Create an Account record and Fetch it via Id


/// FETCH all Account records via SOQL and delete them

*/
Loading