spring_batch_rs/core/
item.rs

1use crate::error::BatchError;
2use serde::{de::DeserializeOwned, Serialize};
3
4/// Represents the result of reading an item from the reader.
5pub type ItemReaderResult<R> = Result<Option<R>, BatchError>;
6
7/// Represents the result of processing an item by the processor.
8pub type ItemProcessorResult<W> = Result<W, BatchError>;
9
10/// Represents the result of writing items by the writer.
11pub type ItemWriterResult = Result<(), BatchError>;
12
13/// A trait for reading items.
14pub trait ItemReader<R> {
15    /// Reads an item from the reader.
16    fn read(&self) -> ItemReaderResult<R>;
17}
18
19/// A trait for processing items.
20pub trait ItemProcessor<R, W> {
21    /// Processes an item and returns the processed result.
22    fn process(&self, item: &R) -> ItemProcessorResult<W>;
23}
24
25/// A trait for writing items.
26pub trait ItemWriter<W> {
27    /// Writes the given items.
28    fn write(&self, items: &[W]) -> ItemWriterResult;
29
30    /// Flushes any buffered data.
31    fn flush(&self) -> ItemWriterResult {
32        Ok(())
33    }
34
35    /// Opens the writer.
36    fn open(&self) -> ItemWriterResult {
37        Ok(())
38    }
39
40    /// Closes the writer.
41    fn close(&self) -> ItemWriterResult {
42        Ok(())
43    }
44}
45
46/// A default implementation of the `ItemProcessor` trait.
47#[derive(Default)]
48pub struct DefaultProcessor;
49
50impl<R: Serialize, W: DeserializeOwned> ItemProcessor<R, W> for DefaultProcessor {
51    /// Processes an item by serializing and deserializing it.
52    fn process(&self, item: &R) -> ItemProcessorResult<W> {
53        // TODO: For performance reason the best is to return directly the item. R and W are of the same type
54        // https://github.com/sboussekeyt/spring-batch-rs/issues/32
55        let serialised = serde_json::to_string(&item).unwrap();
56        let item = serde_json::from_str(&serialised).unwrap();
57        Ok(item)
58    }
59}