spring_batch_rs/item/mongodb/
mongodb_writer.rs1use mongodb::{options::InsertManyOptions, sync::Collection};
2
3use crate::{
4 BatchError,
5 core::item::{ItemWriter, ItemWriterResult},
6};
7
8pub 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 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#[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 pub fn new() -> Self {
44 Self { collection: None }
45 }
46
47 pub fn collection(mut self, collection: &'a Collection<O>) -> MongodbItemWriterBuilder<'a, O> {
57 self.collection = Some(collection);
58 self
59 }
60
61 pub fn build(&self) -> MongodbItemWriter<'a, O> {
67 MongodbItemWriter {
68 collection: self.collection.unwrap(),
69 }
70 }
71}