force 0.2.0

Production-ready Salesforce Platform API client with REST and Bulk API 2.0 support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! UI API object info endpoints.
//!
//! Provides object metadata including field descriptions and picklist values
//! via the Salesforce UI API (`/services/data/vXX.0/ui-api/object-info/`).

#![allow(clippy::doc_markdown)]

use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;

// ─── Response types ───────────────────────────────────────────────────────────

/// Metadata about a Salesforce object returned by the UI API.
///
/// Returned by `object_info()`. Contains field descriptions, label
/// information, and the key prefix used to identify records of this type.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectInfoRepresentation {
    /// The SObject API name (e.g., `"Account"`).
    pub api_name: String,
    /// Singular display label.
    pub label: String,
    /// Plural display label.
    pub label_plural: String,
    /// Three-character key prefix that identifies this object type in record IDs.
    pub key_prefix: Option<String>,
    /// Field metadata map keyed by field API name.
    pub fields: HashMap<String, FieldInfoRepresentation>,
    /// Any additional fields returned by the API.
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// Metadata for a single field on a Salesforce object.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FieldInfoRepresentation {
    /// The field API name (e.g., `"Name"`).
    pub api_name: String,
    /// Human-readable field label.
    pub label: String,
    /// The Salesforce data type string (e.g., `"String"`, `"Picklist"`).
    pub data_type: String,
    /// `true` if this field must have a non-null value on create.
    pub required: bool,
    /// `true` if this field can be updated.
    pub updateable: bool,
    /// `true` if this field can be set on create.
    pub createable: bool,
    /// Related object type information for relationship fields.
    pub reference_to_infos: Vec<ReferenceToInfoRepresentation>,
    /// Any additional fields returned by the API.
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// Information about an object type that a relationship field can reference.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceToInfoRepresentation {
    /// API name of the referenced object type.
    pub api_name: String,
    /// Fields used to display the related record's name.
    pub name_fields: Vec<String>,
    /// Any additional fields returned by the API.
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

/// Batch result containing metadata for multiple Salesforce objects.
///
/// Returned by `object_infos_batch()`.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BatchObjectInfoRepresentation {
    /// `true` if any individual result contained an error.
    pub has_errors: bool,
    /// Individual result entries (may be `ObjectInfoRepresentation` or error objects).
    pub results: Vec<Value>,
    /// Any additional fields returned by the API.
    #[serde(flatten)]
    pub extra: HashMap<String, Value>,
}

// ─── UiHandler<A> implementation ─────────────────────────────────────────────

impl<A: crate::auth::Authenticator> crate::api::ui::UiHandler<A> {
    /// Returns metadata for a single Salesforce object type.
    ///
    /// Calls `GET /ui-api/object-info/{object}`.
    ///
    /// * `object` – the SObject API name (e.g., `"Account"`).
    ///
    /// # Errors
    ///
    /// Returns an error if the object type is not found or the request fails.
    pub async fn object_info(
        &self,
        object: &str,
    ) -> crate::error::Result<ObjectInfoRepresentation> {
        crate::types::validator::validate_sobject_name(object)?;

        let path = format!("object-info/{object}");
        self.get(&path, None, "Failed to fetch object info").await
    }

    /// Returns metadata for multiple Salesforce object types in a single request.
    ///
    /// Calls `GET /ui-api/object-info/batch/{objects}` where `objects` is a
    /// comma-separated list of SObject API names.
    ///
    /// * `objects` – one or more SObject API names.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn object_infos_batch(
        &self,
        objects: &[&str],
    ) -> crate::error::Result<BatchObjectInfoRepresentation> {
        for object in objects {
            crate::types::validator::validate_sobject_name(object)?;
        }

        // ⚡ Bolt: Construct path directly to avoid intermediate `.join(",")` allocation
        let capacity = 18 + objects.iter().map(|s| s.len() + 1).sum::<usize>();
        let mut path = String::with_capacity(capacity);
        path.push_str("object-info/batch/");
        for (i, obj) in objects.iter().enumerate() {
            if i > 0 {
                path.push(',');
            }
            path.push_str(obj);
        }
        self.get(&path, None, "Failed to fetch batch object infos")
            .await
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {

    use super::*;
    use crate::client::builder;
    use crate::test_support::{MockAuthenticator, Must};
    use serde_json::json;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    async fn make_client(server: &MockServer) -> crate::client::ForceClient<MockAuthenticator> {
        let auth = MockAuthenticator::new("test_token", &server.uri());
        builder().authenticate(auth).build().await.must()
    }

    fn account_object_info_json() -> serde_json::Value {
        json!({
            "apiName": "Account",
            "label": "Account",
            "labelPlural": "Accounts",
            "keyPrefix": "001",
            "fields": {
                "Name": {
                    "apiName": "Name",
                    "label": "Account Name",
                    "dataType": "String",
                    "required": true,
                    "updateable": true,
                    "createable": true,
                    "referenceToInfos": []
                },
                "OwnerId": {
                    "apiName": "OwnerId",
                    "label": "Owner ID",
                    "dataType": "Reference",
                    "required": false,
                    "updateable": true,
                    "createable": true,
                    "referenceToInfos": [
                        {
                            "apiName": "User",
                            "nameFields": ["Name"]
                        }
                    ]
                }
            }
        })
    }

    // ── object_info ──────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_object_info_success() {
        let server = MockServer::start().await;
        let client = make_client(&server).await;

        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/ui-api/object-info/Account"))
            .respond_with(ResponseTemplate::new(200).set_body_json(account_object_info_json()))
            .expect(1)
            .mount(&server)
            .await;

        let info = client.ui().object_info("Account").await.must();

        assert_eq!(info.api_name, "Account");
        assert_eq!(info.label, "Account");
        assert_eq!(info.label_plural, "Accounts");
        assert_eq!(info.key_prefix.as_deref(), Some("001"));
        assert!(info.fields.contains_key("Name"));
        assert!(info.fields.contains_key("OwnerId"));
    }

    #[tokio::test]
    async fn test_object_info_not_found() {
        let server = MockServer::start().await;
        let client = make_client(&server).await;

        Mock::given(method("GET"))
            .and(path("/services/data/v60.0/ui-api/object-info/NoSuchObject"))
            .respond_with(ResponseTemplate::new(404).set_body_json(json!([{
                "errorCode": "NOT_FOUND",
                "message": "The requested resource does not exist"
            }])))
            .expect(1)
            .mount(&server)
            .await;

        let result = client.ui().object_info("NoSuchObject").await;
        let Err(err) = result else {
            panic!("Expected an error");
        };
        assert!(
            matches!(
                err,
                crate::error::ForceError::Api(_) | crate::error::ForceError::Http(_)
            ),
            "Expected Api or Http error, got: {err}"
        );
    }

    // ── object_infos_batch ───────────────────────────────────────────────────

    #[tokio::test]
    async fn test_object_infos_batch_success() {
        let server = MockServer::start().await;
        let client = make_client(&server).await;

        let response_body = json!({
            "hasErrors": false,
            "results": [
                account_object_info_json(),
                {
                    "apiName": "Contact",
                    "label": "Contact",
                    "labelPlural": "Contacts",
                    "keyPrefix": "003",
                    "fields": {}
                }
            ]
        });

        Mock::given(method("GET"))
            .and(path(
                "/services/data/v60.0/ui-api/object-info/batch/Account,Contact",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(&response_body))
            .expect(1)
            .mount(&server)
            .await;

        let result = client
            .ui()
            .object_infos_batch(&["Account", "Contact"])
            .await
            .must();

        assert!(!result.has_errors);
        assert_eq!(result.results.len(), 2);
    }

    #[tokio::test]
    async fn test_object_infos_batch_error() {
        let server = MockServer::start().await;
        let client = make_client(&server).await;

        Mock::given(method("GET"))
            .and(path(
                "/services/data/v60.0/ui-api/object-info/batch/Account,BadObject",
            ))
            .respond_with(ResponseTemplate::new(400).set_body_json(json!([{
                "errorCode": "INVALID_TYPE",
                "message": "sObject type 'BadObject' is not supported"
            }])))
            .expect(1)
            .mount(&server)
            .await;

        let result = client
            .ui()
            .object_infos_batch(&["Account", "BadObject"])
            .await;
        let Err(err) = result else {
            panic!("Expected an error");
        };
        assert!(
            matches!(
                err,
                crate::error::ForceError::Api(_) | crate::error::ForceError::Http(_)
            ),
            "Expected Api or Http error, got: {err}"
        );
    }

    // ── unit / deserialization tests ─────────────────────────────────────────

    #[test]
    fn test_object_info_representation_deserialize() {
        let json_str = r#"{
            "apiName": "Opportunity",
            "label": "Opportunity",
            "labelPlural": "Opportunities",
            "keyPrefix": "006",
            "fields": {
                "Name": {
                    "apiName": "Name",
                    "label": "Opportunity Name",
                    "dataType": "String",
                    "required": true,
                    "updateable": true,
                    "createable": true,
                    "referenceToInfos": []
                }
            }
        }"#;

        let info: ObjectInfoRepresentation = serde_json::from_str(json_str).must();
        assert_eq!(info.api_name, "Opportunity");
        assert_eq!(info.label_plural, "Opportunities");
        assert_eq!(info.key_prefix.as_deref(), Some("006"));
        assert!(info.fields.contains_key("Name"));

        let name_field = &info.fields["Name"];
        assert!(name_field.required);
        assert!(name_field.updateable);
        assert!(name_field.createable);
        assert!(name_field.reference_to_infos.is_empty());
    }

    #[test]
    fn test_field_info_representation_deserialize() {
        let json_str = r#"{
            "apiName": "AccountId",
            "label": "Account ID",
            "dataType": "Reference",
            "required": false,
            "updateable": false,
            "createable": true,
            "referenceToInfos": [
                {
                    "apiName": "Account",
                    "nameFields": ["Name"]
                }
            ]
        }"#;

        let field: FieldInfoRepresentation = serde_json::from_str(json_str).must();
        assert_eq!(field.api_name, "AccountId");
        assert_eq!(field.data_type, "Reference");
        assert!(!field.required);
        assert!(!field.updateable);
        assert!(field.createable);
        assert_eq!(field.reference_to_infos.len(), 1);

        let ref_info = &field.reference_to_infos[0];
        assert_eq!(ref_info.api_name, "Account");
        assert_eq!(ref_info.name_fields, vec!["Name"]);
    }

    #[tokio::test]
    async fn test_object_info_invalid_sobject_name() {
        let server = MockServer::start().await;
        let client = make_client(&server).await;

        let result = client.ui().object_info("Account; DROP TABLE").await;
        assert!(result.is_err());
        assert!(
            match result {
                Err(e) => e,
                Ok(_) => panic!("Expected error"),
            }
            .to_string()
            .contains("contains invalid characters")
        );
    }

    #[tokio::test]
    async fn test_object_infos_batch_invalid_sobject_name() {
        let server = MockServer::start().await;
        let client = make_client(&server).await;

        let result = client
            .ui()
            .object_infos_batch(&["Account", "Contact; DROP TABLE"])
            .await;
        assert!(result.is_err());
        assert!(
            match result {
                Err(e) => e,
                Ok(_) => panic!("Expected error"),
            }
            .to_string()
            .contains("contains invalid characters")
        );
    }
}