resourcespace-client 0.1.0

A Rust client for the communicating with ResourceSpace API
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use serde::{Serialize, Serializer};
use serde_with::json::JsonString;
use serde_with::{serde_as, skip_serializing_none};

use crate::client::Client;
use crate::error::RsError;

use super::List;

#[derive(Debug)]
pub struct MetadataApi<'a> {
    client: &'a Client,
}

/// Sub-API for metadata endpoints.
impl<'a> MetadataApi<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// For a given field, return all the available tags (nodes) or selectable options.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`GetFieldOptionsRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn get_field_options(
        &self,
        request: GetFieldOptionsRequest,
    ) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("get_field_options", reqwest::Method::GET, request)
            .await
    }

    /// Find a node ID (entry in a fixed tag field) given the name of the node.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`GetNodeIdRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn get_node_id(
        &self,
        request: GetNodeIdRequest,
    ) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("get_node_id", reqwest::Method::GET, request)
            .await
    }

    /// Get all nodes (fixed keywords) from database for a specific metadata field or parent.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`GetNodesRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn get_nodes(&self, request: GetNodesRequest) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("get_nodes", reqwest::Method::GET, request)
            .await
    }

    /// Add all node IDs (field options) in the list to a resource.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`AddResourceNodesRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn add_resource_nodes(
        &self,
        request: AddResourceNodesRequest,
    ) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("add_resource_nodes", reqwest::Method::POST, request)
            .await
    }

    /// Add all node IDs (field options) in the list to the resources specified.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`AddResourceNodesMultiRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn add_resource_nodes_multi(
        &self,
        request: AddResourceNodesMultiRequest,
    ) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("add_resource_nodes_multi", reqwest::Method::POST, request)
            .await
    }

    /// Create a new node (option for a fixed list field).
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`SetNodeRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn set_node(&self, request: SetNodeRequest) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("set_node", reqwest::Method::POST, request)
            .await
    }

    /// Get metadata field information for all (matching) fields.
    ///
    /// Available from RS version 10.3+ and requires permission `a`.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`GetResourceTypeFieldsRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn get_resource_type_fields(
        &self,
        request: GetResourceTypeFieldsRequest,
    ) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("get_resource_type_fields", reqwest::Method::GET, request)
            .await
    }

    /// Create a metadata field.
    ///
    /// Available from RS version 10.3+ and requires permission `a`.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`CreateResourceTypeFieldRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn create_resource_type_field(
        &self,
        request: CreateResourceTypeFieldRequest,
    ) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("create_resource_type_field", reqwest::Method::POST, request)
            .await
    }

    /// Toggle nodes' active state.
    ///
    /// Available from RS version 10.4+ and requires permission `k`.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`ToggleActiveStatesForNodesRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn toggle_active_state_for_nodes(
        &self,
        request: ToggleActiveStatesForNodesRequest,
    ) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request(
                "toggle_active_state_for_nodes",
                reqwest::Method::POST,
                request,
            )
            .await
    }

    /// Set the value of a metadata field.
    ///
    /// ## Arguments
    /// * `request` - Parameters built via [`UpdateFieldRequest`]
    ///
    /// ## TODO: Returns
    ///
    /// ## TODO: Errors
    ///
    /// ## TODO: Examples
    pub async fn update_field(
        &self,
        request: UpdateFieldRequest,
    ) -> Result<serde_json::Value, RsError> {
        self.client
            .send_request("update_field", reqwest::Method::POST, request)
            .await
    }
}

/// A metadata field identifier, either a numeric ID or a shortname.
///
/// Accepts a `u32` field ID or a string shortname via [`Into`] conversions,
/// making it ergonomic to reference fields at call sites:
///
/// ```no_run
/// FieldIdentifier::from(72)       // numeric ID
/// FieldIdentifier::from("title")  // shortname
/// ```
#[derive(Clone, Debug, PartialEq)]
pub enum FieldIdentifier {
    Id(u32),
    Shortname(String),
}

impl From<u32> for FieldIdentifier {
    fn from(id: u32) -> Self {
        Self::Id(id)
    }
}

impl From<String> for FieldIdentifier {
    fn from(name: String) -> Self {
        Self::Shortname(name)
    }
}

impl From<&str> for FieldIdentifier {
    fn from(name: &str) -> Self {
        Self::Shortname(name.to_string())
    }
}

impl Serialize for FieldIdentifier {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Id(id) => id.serialize(serializer),
            Self::Shortname(name) => name.serialize(serializer),
        }
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct GetFieldOptionsRequest {
    /// The ID or shortname of the metadata field to retrieve options for.
    #[serde(rename = "ref")]
    pub r#ref: FieldIdentifier,
    /// If set, returns additional node information alongside each option.
    pub nodeinfo: Option<bool>,
}

impl GetFieldOptionsRequest {
    pub fn new(r#ref: impl Into<FieldIdentifier>) -> Self {
        Self {
            r#ref: r#ref.into(),
            nodeinfo: None,
        }
    }

    pub fn nodeinfo(mut self, nodeinfo: bool) -> Self {
        self.nodeinfo = Some(nodeinfo);
        self
    }
}

#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct GetNodeIdRequest {
    /// The name of the node to look up.
    pub value: String,
    /// The ID of the resource type field the node belongs to.
    pub resource_type_field: u32,
}

impl GetNodeIdRequest {
    pub fn new(value: impl Into<String>, resource_type_field: u32) -> Self {
        Self {
            value: value.into(),
            resource_type_field,
        }
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct GetNodesRequest {
    /// The ID of the metadata field to retrieve nodes from.
    #[serde(rename = "ref")]
    pub r#ref: u32,
    /// Restrict results to children of this parent node ID.
    pub parent: Option<u32>,
    /// If set, retrieves all descendant nodes recursively.
    pub recursive: Option<bool>,
    /// Number of nodes to skip, used for pagination.
    pub offset: Option<u32>,
    /// Maximum number of nodes to return.
    pub rows: Option<u32>,
    /// Filter nodes by name (partial match).
    pub name: Option<String>,
    /// If set, includes the number of resources using each node.
    pub use_count: Option<bool>,
    /// If set, orders results by the translated node name.
    pub order_by_translated_name: Option<bool>,
}

impl GetNodesRequest {
    pub fn new(r#ref: u32) -> Self {
        Self {
            r#ref,
            parent: None,
            recursive: None,
            offset: None,
            rows: None,
            name: None,
            use_count: None,
            order_by_translated_name: None,
        }
    }

    pub fn parent(mut self, parent: u32) -> Self {
        self.parent = Some(parent);
        self
    }

    pub fn recursive(mut self, recursive: bool) -> Self {
        self.recursive = Some(recursive);
        self
    }

    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    pub fn rows(mut self, rows: u32) -> Self {
        self.rows = Some(rows);
        self
    }

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

    pub fn use_count(mut self, use_count: bool) -> Self {
        self.use_count = Some(use_count);
        self
    }

    pub fn order_by_translated_name(mut self, order_by_translated_name: bool) -> Self {
        self.order_by_translated_name = Some(order_by_translated_name);
        self
    }
}

#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct AddResourceNodesRequest {
    /// The ID of the resource to add nodes to.
    pub resource: u32,
    /// Comma-separated list of node IDs to add to the resource.
    pub nodestring: List<u32>,
}

impl AddResourceNodesRequest {
    pub fn new(resource: u32, nodestring: impl Into<List<u32>>) -> Self {
        Self {
            resource,
            nodestring: nodestring.into(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct AddResourceNodesMultiRequest {
    /// Comma-separated list of resource IDs to add nodes to.
    pub resourceid: List<u32>,
    /// Comma-separated list of node IDs to add to each resource.
    pub nodes: List<u32>,
}

impl AddResourceNodesMultiRequest {
    pub fn new(resourceid: impl Into<List<u32>>, nodes: impl Into<List<u32>>) -> Self {
        Self {
            resourceid: resourceid.into(),
            nodes: nodes.into(),
        }
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct SetNodeRequest {
    /// The ID of an existing node to update, or 0 to create a new one.
    #[serde(rename = "ref")]
    pub r#ref: u32,
    /// The ID of the resource type field this node belongs to.
    pub resource_type_field: u32,
    /// The name of the node.
    pub name: String,
    /// The ID of the parent node, if this is a child node.
    pub parent: Option<String>,
    /// Position used to order this node relative to siblings.
    pub order_by: Option<u32>,
    /// If set, returns the existing node instead of creating a duplicate.
    pub returnexisting: Option<bool>,
}

impl SetNodeRequest {
    pub fn new(r#ref: u32, resource_type_field: u32, name: impl Into<String>) -> Self {
        Self {
            r#ref,
            resource_type_field,
            name: name.into(),
            parent: None,
            order_by: None,
            returnexisting: None,
        }
    }
    pub fn parent(mut self, parent: impl Into<String>) -> Self {
        self.parent = Some(parent.into());
        self
    }

    pub fn order_by(mut self, order_by: u32) -> Self {
        self.order_by = Some(order_by);
        self
    }

    pub fn returnexisting(mut self, returnexisting: bool) -> Self {
        self.returnexisting = Some(returnexisting);
        self
    }
}

#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct GetResourceTypeFieldsRequest {
    /// Comma-separated list of resource type IDs to filter fields by.
    pub by_resource_types: Option<List<u32>>,
    /// Search string to filter fields by name.
    pub find: Option<String>,
    /// Comma-separated list of field type IDs to filter by.
    pub by_types: Option<List<u32>>,
}

impl GetResourceTypeFieldsRequest {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn by_resource_types(mut self, by_resource_types: impl Into<List<u32>>) -> Self {
        self.by_resource_types = Some(by_resource_types.into());
        self
    }

    pub fn find(mut self, find: impl Into<String>) -> Self {
        self.find = Some(find.into());
        self
    }

    pub fn by_types(mut self, by_types: impl Into<List<u32>>) -> Self {
        self.by_types = Some(by_types.into());
        self
    }
}

#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct CreateResourceTypeFieldRequest {
    /// The name of the new metadata field.
    pub name: String,
    /// Comma-separated list of resource type IDs this field should apply to.
    pub resource_types: List<u32>,
    /// The field type, for values see the FIELD_TYPE_* constants.
    pub r#type: String,
}

impl CreateResourceTypeFieldRequest {
    pub fn new(
        name: impl Into<String>,
        resource_types: impl Into<List<u32>>,
        r#type: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            resource_types: resource_types.into(),
            r#type: r#type.into(),
        }
    }
}

#[serde_as]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ToggleActiveStatesForNodesRequest {
    /// JSON-encoded array of node IDs whose active states should be toggled.
    #[serde_as(as = "JsonString")]
    pub refs: Vec<u32>,
}

impl ToggleActiveStatesForNodesRequest {
    pub fn new(refs: impl Into<List<u32>>) -> Self {
        Self {
            refs: refs.into().0,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct UpdateFieldRequest {
    /// The ID of the resource to update.
    pub resource: u32,
    /// The ID or shortname of the metadata field to set a value on.
    pub field: FieldIdentifier,
    /// The new value to assign to the field.
    /// This can be a comma separated list for fixed list option fields.
    #[serde(flatten)]
    pub value: FieldValue,
}

impl UpdateFieldRequest {
    pub fn new(
        resource: u32,
        field: impl Into<FieldIdentifier>,
        value: impl Into<FieldValue>,
    ) -> Self {
        Self {
            resource,
            field: field.into(),
            value: value.into(),
        }
    }
}

/// The value to set for a metadata field.
///
/// Accepts plain text or a list of node IDs via named constructors:
///
/// ```no_run
/// FieldValue::from("hello")          // plain text
/// FieldValue::from("red")            // single option
/// FieldValue::from(42u32)            // single node ID
/// FieldValue::from([1u32, 2, 3])     // multiple node IDs
/// ```
///
/// When constructed from node IDs, the `nodevalues` parameter is
/// automatically set to `true`.
#[derive(Clone, Debug, PartialEq)]
pub enum FieldValue {
    /// A plain text value e.g. "hello"
    Text(String),
    /// A list of node IDs, sets nodevalues = true automatically
    Nodes(List<u32>),
}

impl From<&str> for FieldValue {
    fn from(val: &str) -> Self {
        Self::Text(val.to_string())
    }
}

impl From<String> for FieldValue {
    fn from(val: String) -> Self {
        Self::Text(val)
    }
}

impl From<u32> for FieldValue {
    fn from(val: u32) -> Self {
        Self::Nodes(List::from(val))
    }
}

impl From<Vec<u32>> for FieldValue {
    fn from(val: Vec<u32>) -> Self {
        Self::Nodes(List::from(val))
    }
}

impl<const N: usize> From<[u32; N]> for FieldValue {
    fn from(val: [u32; N]) -> Self {
        Self::Nodes(List::from(val))
    }
}

impl Serialize for FieldValue {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;

        let mut map = serializer.serialize_map(None)?;
        match self {
            Self::Text(text) => {
                map.serialize_entry("value", text)?;
            }
            Self::Nodes(nodes) => {
                map.serialize_entry("value", nodes)?;
                map.serialize_entry("nodevalues", &true)?;
            }
        }
        map.end()
    }
}