Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion assets/js/app.js

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,35 +1,26 @@
use std::collections::HashMap;

use axum::extract::{Query, State};
use axum::Json;

use crate::avored_state::AppState;
use crate::core::application::dtos::api_key_dto::ListApiKeysResponse;
use crate::core::application::dtos::pagination_dto::{PaginatedResponse, PaginationQuery};
use crate::error::Result;
use crate::interfaces::api::api_key::api_key_model_to_response;

pub async fn paginate_api_keys_handler(
State(state): State<AppState>,
Query(params): Query<HashMap<String, String>>,
Query(query): Query<PaginationQuery>,
) -> Result<Json<ListApiKeysResponse>> {
let page = params
.get("page")
.and_then(|v| v.parse().ok())
.unwrap_or(1u64);
let limit = params
.get("limit")
.and_then(|v| v.parse().ok())
.unwrap_or(20u64);
let page = query.current_page();
let per_page = query.per_page();

let (models, total_items) = state.api_key_use_case.list(page, limit).await?;
let total_pages = total_items.div_ceil(limit);
let (models, total) = state.api_key_use_case.list(page, per_page).await?;

let data = models.into_iter().map(api_key_model_to_response).collect();
Ok(Json(ListApiKeysResponse {
Ok(Json(PaginatedResponse {
data,
page,
limit,
total_items,
total_pages,
pagination: crate::core::application::dtos::pagination_dto::Pagination::new(
total, per_page, page,
),
}))
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ use crate::{
core::application::dtos::api_manager_dto::{
EntityRecordResponse, ListEntitiesQuery, ListEntitiesResponse,
},
core::application::dtos::pagination_dto::{PaginatedResponse, Pagination, PaginationQuery},
core::domain::entities::error_message::{ApiErrorResponse, ErrorMessageResponse},
error::{Error, Result},
};

/// Reserved query-parameter keys that must never be treated as attribute filters.
const RESERVED_KEYS: &[&str] = &["entity_type", "page", "limit"];
const RESERVED_KEYS: &[&str] = &["entity_type", "page", "per_page", "page_size", "limit"];

/// `GET /api/v1/entities?entity_type={type}&page={p}&limit={l}[&attr=value…]`
/// `GET /api/v1/entities?entity_type={type}&page={p}&per_page={n}[&attr=value…]`
///
/// Returns a paginated list of dynamic records belonging to the supplied entity
/// type. Any query parameter other than the three reserved ones is interpreted
Expand All @@ -38,30 +39,14 @@ pub async fn paginate_entities_handler(
}));
}

let page = query.page.unwrap_or(1);
let limit = query.limit.unwrap_or(20);

if page == 0 {
return Err(Error::BadRequest(ApiErrorResponse {
status: false,
errors: vec![ErrorMessageResponse {
key: "page".to_string(),
message: "page must be greater than 0".to_string(),
}],
request_id: None,
}));
}

if limit == 0 || limit > 100 {
return Err(Error::BadRequest(ApiErrorResponse {
status: false,
errors: vec![ErrorMessageResponse {
key: "limit".to_string(),
message: "limit must be between 1 and 100".to_string(),
}],
request_id: None,
}));
}
let pagination_query = PaginationQuery {
page: query.page,
per_page: query.per_page,
page_size: query.page_size,
limit: query.limit,
};
let page = pagination_query.current_page();
let per_page = pagination_query.per_page();

// Strip reserved keys from the flat filter map so attribute filters are clean.
for key in RESERVED_KEYS {
Expand All @@ -70,9 +55,9 @@ pub async fn paginate_entities_handler(

// --- Delegate to use case ---

let (records, total_items, total_pages, resolved_limit) = state
let (records, total_items) = state
.entity_use_case
.list_entities(&entity_type, page, limit, query.filters)
.list_entities(&entity_type, page, per_page, query.filters)
.await?;

// --- Shape response ---
Expand All @@ -82,12 +67,9 @@ pub async fn paginate_entities_handler(
.map(|record| shape_record(record, &entity_type))
.collect();

let response = ListEntitiesResponse {
let response = PaginatedResponse {
data,
page,
limit: resolved_limit,
total_items,
total_pages,
pagination: Pagination::new(total_items, per_page, page),
};

Ok(Json(response))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,24 @@ use serde::Deserialize;
pub struct CollectionQuery {
pub entity_id: String,
pub page: Option<u64>,
pub per_page: Option<u64>,
pub page_size: Option<u64>,
pub limit: Option<u64>,
}

pub async fn paginate_collections_handler(
State(state): State<AppState>,
Query(query): Query<CollectionQuery>,
) -> Result<Json<CollectionPaginationResponse>> {
let command = PaginateCollectionCommand {
let pagination_query = crate::core::application::dtos::pagination_dto::PaginationQuery {
page: query.page,
per_page: query.per_page,
page_size: query.page_size,
limit: query.limit,
};
let command = PaginateCollectionCommand {
page: Some(pagination_query.current_page()),
page_size: Some(pagination_query.per_page()),
};

let response = state
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
use crate::avored_state::AppState;
use crate::core::application::dtos::entity_dto::{EntityPaginationResponse, PaginateEntityCommand};
use crate::core::application::dtos::pagination_dto::{Pagination, PaginationQuery};
use crate::error::Result;
use axum::extract::Query;
use axum::{extract::State, Json};

pub async fn paginate_entities_handler(
State(state): State<AppState>,
Query(command): Query<PaginateEntityCommand>,
Query(query): Query<PaginationQuery>,
) -> Result<Json<EntityPaginationResponse>> {
let page = query.current_page();
let per_page = query.per_page();
let command = PaginateEntityCommand {
page: Some(page),
page_size: Some(per_page),
};
let (data, total) = state.entity_use_case.paginate(command).await?;
let response = EntityPaginationResponse {
data: data.into_iter().map(Into::into).collect(),
total,
pagination: Pagination::new(total, per_page, page),
};
Ok(Json(response))
}
114 changes: 114 additions & 0 deletions crates/avored-api/tests/pagination_integration_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
#![allow(clippy::unwrap_used, clippy::expect_used)]

use avored_api::core::domain::entities::user::TokenClaims;
use avored_api::{
avored_state::test_avored_state,
core::domain::entities::entity::StorableEntity,
interfaces::api::{
api_key::paginate_api_keys_handler::paginate_api_keys_handler,
api_manager::paginate_entities_handler::paginate_entities_handler as paginate_dynamic_entities_handler,
collection::paginate_collections_handler::paginate_collections_handler,
email_template::paginate_email_templates_handler::paginate_email_templates_handler,
entity::paginate_entities_handler::paginate_entities_handler,
workflow::list_workflows_handler,
},
};
use axum::{
body::{to_bytes, Body},
http::{Request, StatusCode},
routing::get,
Extension, Router,
};
use chrono::Utc;
use tower::ServiceExt;

fn pagination_api(state: avored_api::avored_state::AppState) -> Router {
let claims = TokenClaims {
sub: "users:pagination-test".to_string(),
name: "Pagination Test".to_string(),
email: "pagination@example.test".to_string(),
iat: Utc::now().timestamp() as usize,
exp: (Utc::now().timestamp() + 3600) as usize,
};

Router::new()
.route("/api/v1/admin/entities", get(paginate_entities_handler))
.route(
"/api/v1/admin/email-templates",
get(paginate_email_templates_handler),
)
.route("/api/v1/admin/api-keys", get(paginate_api_keys_handler))
.route("/api/v1/admin/workflows", get(list_workflows_handler))
.route(
"/api/v1/admin/collection",
get(paginate_collections_handler),
)
.route("/api/v1/entities", get(paginate_dynamic_entities_handler))
.layer(Extension(claims))
.with_state(state)
}

async fn get_json(app: Router, uri: &str) -> (StatusCode, serde_json::Value) {
let response = app
.oneshot(
Request::builder()
.uri(uri)
.body(Body::empty())
.expect("request should be valid"),
)
.await
.expect("request should complete");
let status = response.status();
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("response body should be readable");
(
status,
serde_json::from_slice(&body).expect("response should contain JSON"),
)
}

#[tokio::test]
async fn list_endpoints_share_the_pagination_envelope_and_defaults() {
let state = test_avored_state().await;
let entity = state
.entity_use_case
.create(StorableEntity {
name: "Pagination integration".to_string(),
identifier: "pagination_integration".to_string(),
logged_in_user_email: "pagination@example.test".to_string(),
attributes: Vec::new(),
})
.await
.expect("test entity should be created");
let app = pagination_api(state);
let collection_uri = format!("/api/v1/admin/collection?entity_id={}", entity.id);
let endpoints = [
("/api/v1/admin/entities", 1),
("/api/v1/admin/email-templates", 0),
("/api/v1/admin/api-keys", 0),
("/api/v1/admin/workflows", 0),
(collection_uri.as_str(), 0),
("/api/v1/entities?entity_type=pagination_integration", 0),
];

for (uri, total) in endpoints {
let (status, response) = get_json(app.clone(), uri).await;
assert_eq!(status, StatusCode::OK, "request to {uri} should succeed");
assert!(response["data"].is_array(), "{uri} should return data");
assert_eq!(response["pagination"]["total"], total, "{uri}");
assert_eq!(response["pagination"]["per_page"], 25, "{uri}");
assert_eq!(response["pagination"]["current_page"], 1, "{uri}");
assert_eq!(response["pagination"]["last_page"], 1, "{uri}");
}

let (status, response) = get_json(
app,
"/api/v1/entities?entity_type=pagination_integration&page=2&per_page=10",
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(response["pagination"]["per_page"], 10);
assert_eq!(response["pagination"]["current_page"], 2);
assert_eq!(response["pagination"]["last_page"], 1);
}
15 changes: 10 additions & 5 deletions crates/avored-api/tests/workflow_api_integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,10 @@ async fn workflow_api_supports_authenticated_crud_and_activation() {
.expect("list request should complete");
assert_eq!(list_response.status(), StatusCode::OK);
let list = response_json(list_response).await;
assert_eq!(list["total"], 1);
assert_eq!(list["pagination"]["total"], 1);
assert_eq!(list["pagination"]["per_page"], 10);
assert_eq!(list["pagination"]["current_page"], 1);
assert_eq!(list["pagination"]["last_page"], 1);
assert_eq!(list["data"][0]["id"], id);

let fetch_response = app
Expand Down Expand Up @@ -382,7 +385,8 @@ async fn workflow_execution_history_api_lists_empty_and_paginated_results() {
.expect("history request should complete");
assert_eq!(empty_response.status(), StatusCode::OK);
let empty_history = response_json(empty_response).await;
assert_eq!(empty_history["total"], 0);
assert_eq!(empty_history["pagination"]["total"], 0);
assert_eq!(empty_history["pagination"]["last_page"], 1);
assert_eq!(empty_history["data"].as_array().unwrap().len(), 0);

state
Expand Down Expand Up @@ -414,9 +418,10 @@ async fn workflow_execution_history_api_lists_empty_and_paginated_results() {
.expect("history request should complete");
assert_eq!(history_response.status(), StatusCode::OK);
let history = response_json(history_response).await;
assert_eq!(history["total"], 2);
assert_eq!(history["page"], 1);
assert_eq!(history["page_size"], 1);
assert_eq!(history["pagination"]["total"], 2);
assert_eq!(history["pagination"]["current_page"], 1);
assert_eq!(history["pagination"]["per_page"], 1);
assert_eq!(history["pagination"]["last_page"], 2);
assert_eq!(history["data"][0]["workflow_id"], workflow_id);
assert_eq!(history["data"][0]["status"], "running");
assert_eq!(history["data"][0]["payload"]["record_id"], "customer-456");
Expand Down
3 changes: 2 additions & 1 deletion crates/avored-api/tests/workflow_entity_dispatch_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ async fn wait_for_execution(state: &AppState, workflow_id: &str) {
.find_executions(workflow_id, WorkflowPaginationQuery::default())
.await
.expect("execution history query should succeed");
if history.total > 0 {
if history.pagination.total > 0 {
assert_eq!(history.data[0].status, WorkflowExecutionStatus::Failed);
return;
}
Expand Down Expand Up @@ -161,6 +161,7 @@ async fn entity_create_and_update_dispatch_matching_workflows_without_changing_r
.find_executions(&updated_workflow.id, WorkflowPaginationQuery::default())
.await
.expect("update workflow history should be queryable")
.pagination
.total,
0
);
Expand Down
Loading
Loading