spring_batch_rs/item/mongodb/
mongodb_writer.rs1use mongodb::{options::InsertManyOptions, sync::Collection};
2
3use crate::{
4 core::item::{ItemWriter, ItemWriterResult},
5 BatchError,
6};
7
8pub struct MongodbItemWriter<'a, W> {
10 collection: &'a Collection<W>,
11}
12
13impl<'a, W: serde::Serialize> ItemWriter<W> for MongodbItemWriter<'a, W> {
14 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#[derive(Default)]
37pub struct MongodbItemWriterBuilder<'a, W> {
38 collection: Option<&'a Collection<W>>,
39}
40
41impl<'a, W> MongodbItemWriterBuilder<'a, W> {
42 pub fn new() -> Self {
44 Self { collection: None }
45 }
46
47 pub fn collection(mut self, collection: &'a Collection<W>) -> MongodbItemWriterBuilder<'a, W> {
57 self.collection = Some(collection);
58 self
59 }
60
61 pub fn build(&self) -> MongodbItemWriter<'a, W> {
67 MongodbItemWriter {
68 collection: self.collection.unwrap(),
69 }
70 }
71}