Skip to main content

spring_batch_rs/item/mongodb/
mongodb_writer.rs

1use mongodb::{options::InsertManyOptions, sync::Collection};
2
3use crate::{
4    BatchError,
5    core::item::{ItemWriter, ItemWriterResult},
6};
7
8/// Represents a MongoDB item writer.
9pub struct MongodbItemWriter<'a, O: Send + Sync> {
10    collection: &'a Collection<O>,
11}
12
13impl<O: serde::Serialize + Send + Sync> ItemWriter<O> for MongodbItemWriter<'_, O> {
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: &[O]) -> ItemWriterResult {
24        let opts = InsertManyOptions::builder().ordered(false).build();
25
26        let result = self.collection.insert_many(items).with_options(opts).run();
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, O: Send + Sync> {
38    collection: Option<&'a Collection<O>>,
39}
40
41impl<'a, O: Send + Sync> MongodbItemWriterBuilder<'a, O> {
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<O>) -> MongodbItemWriterBuilder<'a, O> {
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, O> {
67        MongodbItemWriter {
68            collection: self.collection.unwrap(),
69        }
70    }
71}