reinhardt-views 0.1.2

View layer aggregator for viewsets and views-core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! ListAPIView implementation for displaying lists of objects

use crate::viewsets::{FilterConfig, PaginationConfig};
use async_trait::async_trait;
use hyper::Method;
use reinhardt_core::exception::{Error, Result};
use reinhardt_db::orm::{Filter, FilterOperator, FilterValue, Model, QuerySet};
use reinhardt_http::{Request, Response};
use reinhardt_rest::serializers::Serializer;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;

use crate::core::View;

/// ListAPIView for displaying paginated lists of objects
///
/// Similar to Django REST Framework's ListAPIView, this view provides
/// read-only access to a list of model instances with support for
/// pagination, filtering, and ordering.
///
/// # Type Parameters
///
/// * `M` - The model type (must implement `Model`, `Serialize`, `Deserialize`)
/// * `S` - The serializer type (must implement `Serializer`)
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_views::ListAPIView;
/// use reinhardt_db::orm::{Model, QuerySet};
/// use reinhardt_rest::serializers::JsonSerializer;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// struct Article {
///     id: Option<i64>,
///     title: String,
///     content: String,
/// }
///
/// #[derive(Clone)]
/// struct ArticleFields;
///
/// impl reinhardt_db::orm::FieldSelector for ArticleFields {
///     fn with_alias(self, _alias: &str) -> Self {
///         self
///     }
/// }
///
/// impl Model for Article {
///     type PrimaryKey = i64;
///     type Fields = ArticleFields;
///     fn table_name() -> &'static str { "articles" }
///     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
///     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
///     fn new_fields() -> Self::Fields { ArticleFields }
/// }
///
/// let view = ListAPIView::<Article, JsonSerializer<Article>>::new()
///     .with_paginate_by(10)
///     .with_ordering(vec!["-created_at".into()]);
/// ```
pub struct ListAPIView<M, S>
where
	M: Model + Serialize + for<'de> Deserialize<'de> + Send + Sync + Clone,
	S: Serializer<Input = M, Output = String> + Send + Sync,
{
	queryset: Option<QuerySet<M>>,
	pagination_config: Option<PaginationConfig>,
	filter_config: Option<FilterConfig>,
	ordering: Option<Vec<String>>,
	_serializer: PhantomData<S>,
}

impl<M, S> ListAPIView<M, S>
where
	M: Model + Serialize + for<'de> Deserialize<'de> + Send + Sync + Clone + 'static,
	S: Serializer<Input = M, Output = String> + Send + Sync + 'static,
{
	/// Creates a new `ListAPIView` with default settings
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// use reinhardt_views::ListAPIView;
	/// use reinhardt_rest::serializers::JsonSerializer;
	/// # use reinhardt_db::orm::Model;
	/// # use serde::{Serialize, Deserialize};
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Article { id: Option<i64>, title: String }
	/// # #[derive(Clone)]
	/// # struct ArticleFields;
	/// # impl reinhardt_db::orm::FieldSelector for ArticleFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// # impl Model for Article {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = ArticleFields;
	/// #     fn table_name() -> &'static str { "articles" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { ArticleFields }
	/// # }
	///
	/// let view = ListAPIView::<Article, JsonSerializer<Article>>::new();
	/// ```
	pub fn new() -> Self {
		Self {
			queryset: None,
			pagination_config: None,
			filter_config: None,
			ordering: None,
			_serializer: PhantomData,
		}
	}

	/// Sets the queryset for this view
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use reinhardt_views::ListAPIView;
	/// # use reinhardt_db::orm::{Model, QuerySet};
	/// # use reinhardt_rest::serializers::JsonSerializer;
	/// # use serde::{Serialize, Deserialize};
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Article { id: Option<i64>, title: String }
	/// # #[derive(Clone)]
	/// # struct ArticleFields;
	/// # impl reinhardt_db::orm::FieldSelector for ArticleFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// # impl Model for Article {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = ArticleFields;
	/// #     fn table_name() -> &'static str { "articles" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { ArticleFields }
	/// # }
	///
	/// let queryset = QuerySet::<Article>::new();
	/// let view = ListAPIView::<Article, JsonSerializer<Article>>::new()
	///     .with_queryset(queryset);
	/// ```
	pub fn with_queryset(mut self, queryset: QuerySet<M>) -> Self {
		self.queryset = Some(queryset);
		self
	}

	/// Sets the number of items per page for pagination
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use reinhardt_views::ListAPIView;
	/// # use reinhardt_rest::serializers::JsonSerializer;
	/// # use reinhardt_db::orm::Model;
	/// # use serde::{Serialize, Deserialize};
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Article { id: Option<i64>, title: String }
	/// # #[derive(Clone)]
	/// # struct ArticleFields;
	/// # impl reinhardt_db::orm::FieldSelector for ArticleFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// # impl Model for Article {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = ArticleFields;
	/// #     fn table_name() -> &'static str { "articles" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { ArticleFields }
	/// # }
	///
	/// let view = ListAPIView::<Article, JsonSerializer<Article>>::new()
	///     .with_paginate_by(20);
	/// ```
	pub fn with_paginate_by(mut self, page_size: usize) -> Self {
		self.pagination_config = Some(PaginationConfig::page_number(page_size, Some(100)));
		self
	}

	/// Sets the pagination configuration for the view
	///
	/// This method allows setting any pagination type (PageNumber, LimitOffset, Cursor, or None).
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use reinhardt_views::ListAPIView;
	/// # use reinhardt_views::viewsets::PaginationConfig;
	/// # use reinhardt_rest::serializers::JsonSerializer;
	/// # use reinhardt_db::orm::Model;
	/// # use serde::{Serialize, Deserialize};
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Article { id: Option<i64>, title: String }
	/// # #[derive(Clone)]
	/// # struct ArticleFields;
	/// # impl reinhardt_db::orm::FieldSelector for ArticleFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// # impl Model for Article {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = ArticleFields;
	/// #     fn table_name() -> &'static str { "articles" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { ArticleFields }
	/// # }
	///
	/// let view = ListAPIView::<Article, JsonSerializer<Article>>::new()
	///     .with_pagination(PaginationConfig::limit_offset(10, Some(100)));
	/// ```
	pub fn with_pagination(mut self, config: PaginationConfig) -> Self {
		self.pagination_config = Some(config);
		self
	}

	/// Sets the ordering for the queryset
	///
	/// Fields can be prefixed with `-` for descending order.
	///
	/// # Examples
	///
	/// ```rust,no_run
	/// # use reinhardt_views::ListAPIView;
	/// # use reinhardt_rest::serializers::JsonSerializer;
	/// # use reinhardt_db::orm::Model;
	/// # use serde::{Serialize, Deserialize};
	/// # #[derive(Debug, Clone, Serialize, Deserialize)]
	/// # struct Article { id: Option<i64>, title: String }
	/// # #[derive(Clone)]
	/// # struct ArticleFields;
	/// # impl reinhardt_db::orm::FieldSelector for ArticleFields {
	/// #     fn with_alias(self, _alias: &str) -> Self { self }
	/// # }
	/// # impl Model for Article {
	/// #     type PrimaryKey = i64;
	/// #     type Fields = ArticleFields;
	/// #     fn table_name() -> &'static str { "articles" }
	/// #     fn primary_key(&self) -> Option<Self::PrimaryKey> { self.id }
	/// #     fn set_primary_key(&mut self, value: Self::PrimaryKey) { self.id = Some(value); }
	/// #     fn new_fields() -> Self::Fields { ArticleFields }
	/// # }
	///
	/// let view = ListAPIView::<Article, JsonSerializer<Article>>::new()
	///     .with_ordering(vec!["-created_at".into(), "title".into()]);
	/// ```
	pub fn with_ordering(mut self, ordering: Vec<String>) -> Self {
		self.ordering = Some(ordering);
		self
	}

	/// Sets the filter configuration
	pub fn with_filter_config(mut self, filter_config: FilterConfig) -> Self {
		self.filter_config = Some(filter_config);
		self
	}

	/// Gets the queryset, creating a default one if not set
	fn get_queryset(&self) -> QuerySet<M> {
		self.queryset.clone().unwrap_or_default()
	}

	/// Builds a filtered queryset with ordering applied, before pagination.
	fn get_filtered_queryset(&self, request: &Request) -> QuerySet<M> {
		let mut queryset = self.get_queryset();

		// Apply ordering if configured
		if let Some(ref ordering) = self.ordering {
			let order_fields: Vec<&str> = ordering.iter().map(|s| s.as_str()).collect();
			queryset = queryset.order_by(&order_fields);
		}

		// Apply filtering based on request query parameters
		if let Some(ref filter_config) = self.filter_config {
			for field in &filter_config.filterable_fields {
				if let Some(value) = request.query_params.get(field) {
					let filter = Filter::new(
						field.clone(),
						FilterOperator::Eq,
						FilterValue::String(value.clone()),
					);
					queryset = queryset.filter(filter);
				}
			}
		}

		queryset
	}

	/// Gets the objects to display with pagination applied.
	async fn get_objects(&self, request: &Request) -> Result<Vec<M>> {
		let mut queryset = self.get_filtered_queryset(request);

		// Apply pagination based on request parameters
		if let Some(ref pagination) = self.pagination_config {
			match pagination {
				PaginationConfig::PageNumber { page_size, .. } => {
					let page = request
						.query_params
						.get("page")
						.and_then(|p| p.parse::<usize>().ok())
						.unwrap_or(1);
					queryset = queryset.paginate(page, *page_size);
				}
				PaginationConfig::LimitOffset {
					default_limit,
					max_limit,
				} => {
					let limit = request
						.query_params
						.get("limit")
						.and_then(|l| l.parse::<usize>().ok())
						.unwrap_or(*default_limit)
						.min(max_limit.unwrap_or(usize::MAX));
					let offset = request
						.query_params
						.get("offset")
						.and_then(|o| o.parse::<usize>().ok())
						.unwrap_or(0);
					queryset = queryset.offset(offset).limit(limit);
				}
				PaginationConfig::Cursor { page_size, .. } => {
					// For cursor pagination, just apply page_size as limit
					queryset = queryset.limit(*page_size);
				}
				PaginationConfig::None => {
					// No pagination - return all objects
				}
			}
		}

		queryset.all().await.map_err(|e| Error::Http(e.to_string()))
	}
}

impl<M, S> Default for ListAPIView<M, S>
where
	M: Model + Serialize + for<'de> Deserialize<'de> + Send + Sync + Clone + 'static,
	S: Serializer<Input = M, Output = String> + Send + Sync + 'static,
{
	fn default() -> Self {
		Self::new()
	}
}

#[async_trait]
impl<M, S> View for ListAPIView<M, S>
where
	M: Model + Serialize + for<'de> Deserialize<'de> + Send + Sync + Clone + 'static,
	S: Serializer<Input = M, Output = String> + Send + Sync + 'static + Default,
{
	async fn dispatch(&self, request: Request) -> Result<Response> {
		match request.method {
			Method::GET | Method::HEAD => {
				let objects = self.get_objects(&request).await?;

				// Serialize the objects
				let serializer = S::default();
				let serialized = objects
					.iter()
					.map(|obj| {
						serializer
							.serialize(obj)
							.map_err(|e| Error::Http(e.to_string()))
					})
					.collect::<Result<Vec<_>>>()?;

				// Build response with pagination metadata
				let results: Vec<serde_json::Value> = serialized
					.iter()
					.filter_map(|s| serde_json::from_str::<serde_json::Value>(s).ok())
					.collect();

				let response_body = if let Some(ref pagination) = self.pagination_config {
					// Get total count from the filtered queryset (before pagination)
					let total_count = self
						.get_filtered_queryset(&request)
						.count()
						.await
						.map_err(|e| Error::Http(e.to_string()))?;

					match pagination {
						PaginationConfig::PageNumber { page_size, .. } => {
							let page = request
								.query_params
								.get("page")
								.and_then(|p| p.parse::<usize>().ok())
								.unwrap_or(1);
							let has_next = page.saturating_mul(*page_size) < total_count;
							serde_json::json!({
								"count": total_count,
								"page": page,
								"page_size": page_size,
								"next": if has_next { Some(format!("?page={}", page + 1)) } else { None::<String> },
								"previous": if page > 1 { Some(format!("?page={}", page - 1)) } else { None::<String> },
								"results": results
							})
						}
						PaginationConfig::LimitOffset { .. } => {
							let offset = request
								.query_params
								.get("offset")
								.and_then(|o| o.parse::<usize>().ok())
								.unwrap_or(0);
							let limit = request
								.query_params
								.get("limit")
								.and_then(|l| l.parse::<usize>().ok())
								.unwrap_or(10);
							let has_next = offset.saturating_add(limit) < total_count;
							serde_json::json!({
								"count": total_count,
								"offset": offset,
								"limit": limit,
								"next": if has_next { Some(format!("?offset={}&limit={}", offset.saturating_add(limit), limit)) } else { None::<String> },
								"previous": if offset > 0 { Some(format!("?offset={}&limit={}", offset.saturating_sub(limit), limit)) } else { None::<String> },
								"results": results
							})
						}
						_ => {
							serde_json::json!({
								"count": total_count,
								"results": results
							})
						}
					}
				} else {
					serde_json::json!(results)
				};

				Response::ok().with_json(&response_body)
			}
			_ => Err(Error::MethodNotAllowed(format!(
				"Method {} not allowed",
				request.method
			))),
		}
	}

	fn allowed_methods(&self) -> Vec<&'static str> {
		vec!["GET", "HEAD", "OPTIONS"]
	}
}