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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Common Salesforce API response types.
//!
//! This module contains response types used across different Salesforce APIs,
//! including CRUD operation responses and error structures.

use crate::error::ApiError;
use crate::types::SalesforceId;
use serde::{Deserialize, Serialize};

/// Response from a create operation.
///
/// When creating a record in Salesforce, the API returns information about
/// whether the operation succeeded, the ID of the created record (if successful),
/// and any errors that occurred.
///
/// # Examples
///
/// ```
/// use force::types::{ApiError, CreateResponse, SalesforceId};
///
/// // Successful create
/// let response = CreateResponse {
///     id: Some(SalesforceId::new("001000000000001AAA").unwrap()),
///     success: true,
///     errors: vec![],
/// };
/// assert!(response.is_success());
///
/// // Failed create
/// let response = CreateResponse {
///     id: None,
///     success: false,
///     errors: vec![
///         ApiError {
///             message: "Required fields missing".to_string(),
///             error_code: "REQUIRED_FIELD_MISSING".to_string(),
///             fields: vec!["Name".to_string()],
///         }
///     ],
/// };
/// assert!(!response.is_success());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateResponse {
    /// The ID of the created record (present only if success is true).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<SalesforceId>,

    /// Whether the create operation succeeded.
    pub success: bool,

    /// List of errors (empty if success is true).
    #[serde(default)]
    pub errors: Vec<ApiError>,
}

impl CreateResponse {
    /// Creates a successful response with the given ID.
    #[must_use]
    pub fn success(id: SalesforceId) -> Self {
        Self {
            id: Some(id),
            success: true,
            errors: Vec::new(),
        }
    }

    /// Creates a failed response with the given errors.
    #[must_use]
    pub fn failure(errors: Vec<ApiError>) -> Self {
        Self {
            id: None,
            success: false,
            errors,
        }
    }

    /// Returns true if the operation succeeded.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        self.success
    }

    /// Returns true if the operation failed.
    #[must_use]
    pub const fn is_failure(&self) -> bool {
        !self.success
    }
}

/// Generates a simple success/failure response type with `success: bool` and `errors: Vec<ApiError>`.
///
/// `UpdateResponse` and `DeleteResponse` are structurally identical — this macro
/// eliminates the copy-paste while keeping them as distinct types (Salesforce could
/// diverge them in the future).
macro_rules! define_simple_response {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
        #[serde(rename_all = "camelCase")]
        pub struct $name {
            /// Whether the operation succeeded.
            pub success: bool,

            /// List of errors (empty if success is true).
            #[serde(default)]
            pub errors: Vec<ApiError>,
        }

        impl $name {
            /// Creates a successful response.
            #[must_use]
            pub const fn success() -> Self {
                Self {
                    success: true,
                    errors: Vec::new(),
                }
            }

            /// Creates a failed response with the given errors.
            #[must_use]
            pub fn failure(errors: Vec<ApiError>) -> Self {
                Self {
                    success: false,
                    errors,
                }
            }

            /// Returns true if the operation succeeded.
            #[must_use]
            pub const fn is_success(&self) -> bool {
                self.success
            }

            /// Returns true if the operation failed.
            #[must_use]
            pub const fn is_failure(&self) -> bool {
                !self.success
            }
        }
    };
}

define_simple_response!(
    /// Response from an update operation.
    ///
    /// Update operations return only a success flag and any errors.
    /// The ID is not returned since it's already known (it was in the request).
    ///
    /// # Examples
    ///
    /// ```
    /// use force::types::UpdateResponse;
    ///
    /// let response = UpdateResponse {
    ///     success: true,
    ///     errors: vec![],
    /// };
    /// assert!(response.is_success());
    /// ```
    UpdateResponse
);

define_simple_response!(
    /// Response from a delete operation.
    ///
    /// Delete operations return only a success flag and any errors.
    ///
    /// # Examples
    ///
    /// ```
    /// use force::types::DeleteResponse;
    ///
    /// let response = DeleteResponse {
    ///     success: true,
    ///     errors: vec![],
    /// };
    /// assert!(response.is_success());
    /// ```
    DeleteResponse
);

/// Response from an upsert operation.
///
/// Upsert operations can either create a new record or update an existing one.
/// The response indicates which action was taken.
///
/// # Examples
///
/// ```
/// use force::types::{UpsertResponse, SalesforceId};
///
/// // Created a new record
/// let response = UpsertResponse {
///     id: SalesforceId::new("001000000000001AAA").unwrap(),
///     success: true,
///     created: true,
///     errors: vec![],
/// };
/// assert!(response.is_created());
///
/// // Updated existing record
/// let response = UpsertResponse {
///     id: SalesforceId::new("001000000000001AAA").unwrap(),
///     success: true,
///     created: false,
///     errors: vec![],
/// };
/// assert!(response.is_updated());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpsertResponse {
    /// The ID of the record (created or updated).
    pub id: SalesforceId,

    /// Whether the upsert operation succeeded.
    pub success: bool,

    /// True if a new record was created, false if existing was updated.
    pub created: bool,

    /// List of errors (empty if success is true).
    #[serde(default)]
    pub errors: Vec<ApiError>,
}

impl UpsertResponse {
    /// Creates a successful response for a newly created record.
    #[must_use]
    pub const fn created(id: SalesforceId) -> Self {
        Self {
            id,
            success: true,
            created: true,
            errors: Vec::new(),
        }
    }

    /// Creates a successful response for an updated record.
    #[must_use]
    pub const fn updated(id: SalesforceId) -> Self {
        Self {
            id,
            success: true,
            created: false,
            errors: Vec::new(),
        }
    }

    /// Creates a failed response with the given ID and errors.
    #[must_use]
    pub fn failure(id: SalesforceId, errors: Vec<ApiError>) -> Self {
        Self {
            id,
            success: false,
            created: false,
            errors,
        }
    }

    /// Returns true if the operation succeeded.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        self.success
    }

    /// Returns true if the operation failed.
    #[must_use]
    pub const fn is_failure(&self) -> bool {
        !self.success
    }

    /// Returns true if a new record was created.
    #[must_use]
    pub const fn is_created(&self) -> bool {
        self.created
    }

    /// Returns true if an existing record was updated.
    #[must_use]
    pub const fn is_updated(&self) -> bool {
        !self.created
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::Must;

    // RED PHASE - Write failing tests first

    #[test]
    fn test_create_response_success() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let response = CreateResponse::success(id.clone());

        assert!(response.is_success());
        assert!(!response.is_failure());
        assert_eq!(response.id, Some(id));
        assert!(response.errors.is_empty());
    }

    #[test]
    fn test_create_response_failure() {
        let errors = vec![ApiError::new("Test error", "TEST_ERROR")];
        let response = CreateResponse::failure(errors.clone());

        assert!(!response.is_success());
        assert!(response.is_failure());
        assert_eq!(response.id, None);
        assert_eq!(response.errors, errors);
    }

    #[test]
    fn test_create_response_serialize() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let response = CreateResponse::success(id);

        let json = serde_json::to_string(&response).must();
        assert!(json.contains("\"success\":true"));
        assert!(json.contains("001000000000001AAA"));
    }

    #[test]
    fn test_create_response_deserialize() {
        let json = r#"{
            "id": "001000000000001AAA",
            "success": true,
            "errors": []
        }"#;

        let response: CreateResponse = serde_json::from_str(json).must();
        assert!(response.is_success());
        assert!(response.id.is_some());
    }

    #[test]
    fn test_update_response_success() {
        let response = UpdateResponse::success();

        assert!(response.is_success());
        assert!(!response.is_failure());
        assert!(response.errors.is_empty());
    }

    #[test]
    fn test_update_response_failure() {
        let errors = vec![ApiError::new("Update failed", "UPDATE_ERROR")];
        let response = UpdateResponse::failure(errors.clone());

        assert!(!response.is_success());
        assert!(response.is_failure());
        assert_eq!(response.errors, errors);
    }

    #[test]
    fn test_delete_response_success() {
        let response = DeleteResponse::success();

        assert!(response.is_success());
        assert!(!response.is_failure());
        assert!(response.errors.is_empty());
    }

    #[test]
    fn test_delete_response_failure() {
        let errors = vec![ApiError::new("Delete failed", "DELETE_ERROR")];
        let response = DeleteResponse::failure(errors.clone());

        assert!(!response.is_success());
        assert!(response.is_failure());
        assert_eq!(response.errors, errors);
    }

    #[test]
    fn test_upsert_response_created() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let response = UpsertResponse::created(id.clone());

        assert!(response.is_success());
        assert!(response.is_created());
        assert!(!response.is_updated());
        assert_eq!(response.id, id);
        assert!(response.errors.is_empty());
    }

    #[test]
    fn test_upsert_response_updated() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let response = UpsertResponse::updated(id.clone());

        assert!(response.is_success());
        assert!(!response.is_created());
        assert!(response.is_updated());
        assert_eq!(response.id, id);
        assert!(response.errors.is_empty());
    }

    #[test]
    fn test_upsert_response_failure() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let errors = vec![ApiError::new("Upsert failed", "UPSERT_ERROR")];
        let response = UpsertResponse::failure(id.clone(), errors.clone());

        assert!(!response.is_success());
        assert!(response.is_failure());
        assert_eq!(response.id, id);
        assert_eq!(response.errors, errors);
    }

    #[test]
    fn test_api_error_new() {
        let error = ApiError::new("Test message", "TEST_CODE");

        assert_eq!(error.message, "Test message");
        assert_eq!(error.error_code, "TEST_CODE");
        assert!(error.fields.is_empty());
    }

    #[test]
    fn test_api_error_with_fields() {
        let fields = vec!["Name".to_string(), "Email".to_string()];
        let error =
            ApiError::with_fields("Missing fields", "REQUIRED_FIELD_MISSING", fields.clone());

        assert_eq!(error.message, "Missing fields");
        assert_eq!(error.error_code, "REQUIRED_FIELD_MISSING");
        assert_eq!(error.fields, fields);
    }

    #[test]
    fn test_api_error_serialize() {
        let error = ApiError::with_fields(
            "Required fields missing",
            "REQUIRED_FIELD_MISSING",
            vec!["Name".to_string()],
        );

        let json = serde_json::to_string(&error).must();
        assert!(json.contains("\"errorCode\":\"REQUIRED_FIELD_MISSING\""));
        assert!(json.contains("\"message\":\"Required fields missing\""));
        assert!(json.contains("\"fields\""));
    }

    #[test]
    fn test_api_error_deserialize() {
        let json = r#"{
            "message": "Required fields are missing: [Name]",
            "statusCode": "REQUIRED_FIELD_MISSING",
            "fields": ["Name"]
        }"#;

        let error: ApiError = serde_json::from_str(json).must();
        assert_eq!(error.error_code, "REQUIRED_FIELD_MISSING");
        assert_eq!(error.fields, vec!["Name"]);
    }

    #[test]
    fn test_response_roundtrip_serialization() {
        let id = SalesforceId::new("001000000000001AAA").must();
        let original = CreateResponse::success(id);

        let json = serde_json::to_string(&original).must();
        let deserialized: CreateResponse = serde_json::from_str(&json).must();

        assert_eq!(original, deserialized);
    }

    #[test]
    fn test_empty_errors_serialization() {
        let response = UpdateResponse::success();
        let json = serde_json::to_string(&response).must();

        // Empty errors array should still be serialized
        let parsed: serde_json::Value = serde_json::from_str(&json).must();
        assert!(parsed.get("errors").is_some());
    }
}