spring_batch_rs/item/mongodb/
mongodb_writer.rs

1use mongodb::{options::InsertManyOptions, sync::Collection};
2
3use crate::{
4    core::item::{ItemWriter, ItemWriterResult},
5    BatchError,
6};
7
8/// Represents a MongoDB item writer.
9pub struct MongodbItemWriter<'a, W> {
10    collection: &'a Collection<W>,
11}
12
13impl<'a, W: serde::Serialize> ItemWriter<W> for MongodbItemWriter<'a, W> {
14    /// Writes the items to the MongoDB collection.
15    ///
16    /// # Arguments
17    ///
18    /// * `items` - The items to be written.
19    ///
20    /// # Returns
21    ///
22    /// Returns an `ItemWriterResult` indicating the result of the write operation.
23    fn write(&self, items: &[W]) -> ItemWriterResult {
24        let opts = InsertManyOptions::builder().ordered(false).build();
25
26        let result = self.collection.insert_many(items, opts);
27
28        match result {
29            Ok(_ser) => Ok(()),
30            Err(error) => Err(BatchError::ItemWriter(error.to_string())),
31        }
32    }
33}
34
35/// Builder for `MongodbItemWriter`.
36#[derive(Default)]
37pub struct MongodbItemWriterBuilder<'a, W> {
38    collection: Option<&'a Collection<W>>,
39}
40
41impl<'a, W> MongodbItemWriterBuilder<'a, W> {
42    /// Creates a new `MongodbItemWriterBuilder` instance.
43    pub fn new() -> Self {
44        Self { collection: None }
45    }
46
47    /// Sets the MongoDB collection for the writer.
48    ///
49    /// # Arguments
50    ///
51    /// * `collection` - The MongoDB collection to write to.
52    ///
53    /// # Returns
54    ///
55    /// Returns the updated `MongodbItemWriterBuilder` instance.
56    pub fn collection(mut self, collection: &'a Collection<W>) -> MongodbItemWriterBuilder<'a, W> {
57        self.collection = Some(collection);
58        self
59    }
60
61    /// Builds a `MongodbItemWriter` instance.
62    ///
63    /// # Returns
64    ///
65    /// Returns a `MongodbItemWriter` instance with the specified configuration.
66    pub fn build(&self) -> MongodbItemWriter<'a, W> {
67        MongodbItemWriter {
68            collection: self.collection.unwrap(),
69        }
70    }
71}