netbox 0.3.3

ergonomic rust client for NetBox 4.x REST 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
//! generic api resource wrapper for standard netbox crud endpoints.

use crate::Client;
use crate::error::Result;
use crate::pagination::{Page, Paginator};
use crate::query::QueryBuilder;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::borrow::Cow;

/// generic resource wrapper for list/get/create/update/patch/delete operations.
#[derive(Clone)]
pub struct Resource<T> {
    client: Client,
    path: Cow<'static, str>,
    _marker: std::marker::PhantomData<T>,
}

/// bulk update wrapper that includes an id with the update payload.
#[derive(Debug, Clone, Serialize)]
pub struct BulkUpdate<T> {
    /// resource id.
    pub id: u64,
    /// update payload to serialize alongside the id.
    #[serde(flatten)]
    pub data: T,
}

impl<T> BulkUpdate<T> {
    /// create a new bulk update entry.
    pub fn new(id: u64, data: T) -> Self {
        Self { id, data }
    }
}

/// bulk delete wrapper that includes the id to delete.
#[derive(Debug, Clone, Serialize)]
pub struct BulkDelete {
    /// resource id.
    pub id: u64,
}

impl BulkDelete {
    /// create a new bulk delete entry.
    pub fn new(id: u64) -> Self {
        Self { id }
    }
}

impl<T> Resource<T>
where
    T: DeserializeOwned,
{
    pub(crate) fn new(client: Client, path: impl Into<Cow<'static, str>>) -> Self {
        Self {
            client,
            path: path.into(),
            _marker: std::marker::PhantomData,
        }
    }

    /// create a resource with a dynamic path.
    pub fn dynamic(client: Client, path: impl Into<String>) -> Self {
        Self {
            client,
            path: Cow::Owned(path.into()),
            _marker: std::marker::PhantomData,
        }
    }

    /// list all resources for this endpoint.
    pub async fn list(&self, query: Option<QueryBuilder>) -> Result<Page<T>> {
        let query = query.unwrap_or_default();
        self.client
            .get_with_params(self.path.as_ref(), &query)
            .await
    }

    /// get a paginator for iterating through all resources.
    pub fn paginate(&self, query: Option<QueryBuilder>) -> Result<Paginator<T>> {
        let path = if let Some(q) = query {
            let query_string = serde_urlencoded::to_string(&q)?;
            if query_string.is_empty() {
                self.path.to_string()
            } else {
                format!(
                    "{}?{}",
                    self.path.as_ref().trim_end_matches('/'),
                    query_string
                )
            }
        } else {
            self.path.to_string()
        };
        Ok(Paginator::new(self.client.clone(), path))
    }

    /// get a resource by id.
    pub async fn get(&self, id: u64) -> Result<T> {
        self.client
            .get(&format!("{}{}/", self.path.as_ref(), id))
            .await
    }

    /// create a resource.
    pub async fn create<B>(&self, body: &B) -> Result<T>
    where
        B: Serialize,
    {
        self.client.post(self.path.as_ref(), body).await
    }

    /// create resources in bulk.
    pub async fn bulk_create<B>(&self, body: &[B]) -> Result<Vec<T>>
    where
        B: Serialize,
    {
        self.client.post(self.path.as_ref(), body).await
    }

    /// update a resource (full update).
    pub async fn update<B>(&self, id: u64, body: &B) -> Result<T>
    where
        B: Serialize,
    {
        self.client
            .put(&format!("{}{}/", self.path.as_ref(), id), body)
            .await
    }

    /// update resources in bulk (full update).
    pub async fn bulk_update<B>(&self, body: &[B]) -> Result<Vec<T>>
    where
        B: Serialize,
    {
        self.client.put(self.path.as_ref(), body).await
    }

    /// partially update a resource.
    pub async fn patch<B>(&self, id: u64, body: &B) -> Result<T>
    where
        B: Serialize,
    {
        self.client
            .patch(&format!("{}{}/", self.path.as_ref(), id), body)
            .await
    }

    /// partially update resources in bulk.
    pub async fn bulk_patch<B>(&self, body: &[B]) -> Result<Vec<T>>
    where
        B: Serialize,
    {
        self.client.patch(self.path.as_ref(), body).await
    }

    /// delete a resource.
    pub async fn delete(&self, id: u64) -> Result<()> {
        self.client
            .delete(&format!("{}{}/", self.path.as_ref(), id))
            .await
    }

    /// delete resources in bulk.
    pub async fn bulk_delete<B>(&self, body: &[B]) -> Result<()>
    where
        B: Serialize,
    {
        self.client.delete_with_body(self.path.as_ref(), body).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ClientConfig;
    use httpmock::Method::GET;
    use httpmock::{Method::DELETE, Method::PATCH, Method::POST, Method::PUT, MockServer};

    fn test_client() -> Client {
        let config = ClientConfig::new("https://netbox.example.com", "token");
        Client::new(config).unwrap()
    }

    #[test]
    fn paginate_without_query_uses_base_path() {
        let resource: Resource<serde_json::Value> = Resource::new(test_client(), "dcim/devices/");
        let paginator = resource.paginate(None).unwrap();
        assert_eq!(paginator.next_url(), Some("dcim/devices/"));
    }

    #[test]
    fn dynamic_resource_accepts_owned_paths() {
        let resource: Resource<serde_json::Value> =
            Resource::dynamic(test_client(), "dcim/devices/".to_string());
        let paginator = resource.paginate(None).unwrap();
        assert_eq!(paginator.next_url(), Some("dcim/devices/"));
    }

    #[test]
    fn paginate_with_query_encodes_path() {
        let resource: Resource<serde_json::Value> = Resource::new(test_client(), "dcim/devices/");
        let query = QueryBuilder::new().filter("status", "active").limit(10);
        let paginator = resource.paginate(Some(query)).unwrap();
        let query = QueryBuilder::new().filter("status", "active").limit(10);
        let expected_query = serde_urlencoded::to_string(&query).expect("query should serialize");
        let expected = if expected_query.is_empty() {
            "dcim/devices/".to_string()
        } else {
            format!("dcim/devices?{}", expected_query)
        };
        let actual = paginator.next_url().expect("expected paginator url");
        let (actual_path, actual_query) = actual.split_once('?').unwrap_or((actual, ""));
        let (expected_path, expected_query) =
            expected.split_once('?').unwrap_or((expected.as_str(), ""));
        assert_eq!(actual_path, expected_path);

        let mut actual_pairs: Vec<(String, String)> =
            url::form_urlencoded::parse(actual_query.as_bytes())
                .into_owned()
                .collect();
        let mut expected_pairs: Vec<(String, String)> =
            url::form_urlencoded::parse(expected_query.as_bytes())
                .into_owned()
                .collect();
        actual_pairs.sort();
        expected_pairs.sort();
        assert_eq!(actual_pairs, expected_pairs);
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn resource_crud_calls_expected_paths() {
        let server = MockServer::start();
        let base_url = server.base_url();
        let config = ClientConfig::new(&base_url, "token").with_max_retries(0);
        let client = Client::new(config).unwrap();
        let resource: Resource<serde_json::Value> = Resource::new(client, "dcim/devices/");

        let list_response = serde_json::json!({
            "count": 1,
            "next": null,
            "previous": null,
            "results": [{"id": 1}]
        });

        server.mock(|when, then| {
            when.method(GET).path("/api/dcim/devices/");
            then.status(200).json_body(list_response.clone());
        });

        server.mock(|when, then| {
            when.method(GET).path("/api/dcim/devices/1/");
            then.status(200).json_body(serde_json::json!({"id": 1}));
        });

        server.mock(|when, then| {
            when.method(POST).path("/api/dcim/devices/");
            then.status(201).json_body(serde_json::json!({"id": 2}));
        });

        server.mock(|when, then| {
            when.method(PUT).path("/api/dcim/devices/1/");
            then.status(200)
                .json_body(serde_json::json!({"id": 1, "updated": true}));
        });

        server.mock(|when, then| {
            when.method(PATCH).path("/api/dcim/devices/1/");
            then.status(200)
                .json_body(serde_json::json!({"id": 1, "patched": true}));
        });

        server.mock(|when, then| {
            when.method(DELETE).path("/api/dcim/devices/1/");
            then.status(204);
        });

        let page = resource.list(None).await.unwrap();
        assert_eq!(page.count, 1);
        assert_eq!(page.results[0]["id"], 1);

        let item = resource.get(1u64).await.unwrap();
        assert_eq!(item["id"], 1);

        let created = resource
            .create(&serde_json::json!({"name": "device"}))
            .await
            .unwrap();
        assert_eq!(created["id"], 2);

        let updated = resource
            .update(1u64, &serde_json::json!({"name": "device"}))
            .await
            .unwrap();
        assert_eq!(updated["updated"], true);

        let patched = resource
            .patch(1u64, &serde_json::json!({"name": "device"}))
            .await
            .unwrap();
        assert_eq!(patched["patched"], true);

        resource.delete(1u64).await.unwrap();
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn resource_bulk_calls_expected_paths() {
        let server = MockServer::start();
        let base_url = server.base_url();
        let config = ClientConfig::new(&base_url, "token").with_max_retries(0);
        let client = Client::new(config).unwrap();
        let resource: Resource<serde_json::Value> = Resource::new(client, "dcim/devices/");

        let bulk_response = serde_json::json!([{"id": 1}, {"id": 2}]);

        server.mock(|when, then| {
            when.method(POST)
                .path("/api/dcim/devices/")
                .json_body(serde_json::json!([{"name": "a"}, {"name": "b"}]));
            then.status(201).json_body(bulk_response.clone());
        });

        server.mock(|when, then| {
            when.method(PUT)
                .path("/api/dcim/devices/")
                .json_body(serde_json::json!([{"id": 1}, {"id": 2}]));
            then.status(200).json_body(bulk_response.clone());
        });

        server.mock(|when, then| {
            when.method(PATCH)
                .path("/api/dcim/devices/")
                .json_body(serde_json::json!([{"id": 1}, {"id": 2}]));
            then.status(200).json_body(bulk_response.clone());
        });

        server.mock(|when, then| {
            when.method(DELETE)
                .path("/api/dcim/devices/")
                .json_body(serde_json::json!([{"id": 1}, {"id": 2}]));
            then.status(204);
        });

        let created = resource
            .bulk_create(&[
                serde_json::json!({"name": "a"}),
                serde_json::json!({"name": "b"}),
            ])
            .await
            .unwrap();
        assert_eq!(created.len(), 2);

        let updated = resource
            .bulk_update(&[serde_json::json!({"id": 1}), serde_json::json!({"id": 2})])
            .await
            .unwrap();
        assert_eq!(updated.len(), 2);

        let patched = resource
            .bulk_patch(&[serde_json::json!({"id": 1}), serde_json::json!({"id": 2})])
            .await
            .unwrap();
        assert_eq!(patched.len(), 2);

        let deleted = resource
            .bulk_delete(&[serde_json::json!({"id": 1}), serde_json::json!({"id": 2})])
            .await;
        assert!(deleted.is_ok());
    }

    #[cfg_attr(miri, ignore)]
    #[tokio::test]
    async fn list_with_query_encodes_parameters() {
        let server = MockServer::start();
        let base_url = server.base_url();
        let config = ClientConfig::new(&base_url, "token").with_max_retries(0);
        let client = Client::new(config).unwrap();
        let resource: Resource<serde_json::Value> = Resource::new(client, "dcim/devices/");

        let list_response = serde_json::json!({
            "count": 0,
            "next": null,
            "previous": null,
            "results": []
        });

        server.mock(|when, then| {
            let query = QueryBuilder::new().limit(5);
            let query_string = serde_urlencoded::to_string(&query).expect("query should serialize");
            let pairs = url::form_urlencoded::parse(query_string.as_bytes())
                .into_owned()
                .collect::<Vec<_>>();

            let mut when = when.method(GET).path("/api/dcim/devices/");
            for (key, value) in pairs {
                when = when.query_param(key, value);
            }
            then.status(200).json_body(list_response);
        });

        let query = QueryBuilder::new().limit(5);
        let page = resource.list(Some(query)).await.unwrap();
        assert_eq!(page.count, 0);
    }
}