Skip to content

Commit

Permalink
Fix price endpoint (#151)
Browse files Browse the repository at this point in the history
Replaces the logic in the `price` endpoint with the adpator.

Signed-off-by: Rémy Greinhofer <[email protected]>
  • Loading branch information
rgreinho authored Oct 31, 2024
1 parent 2bcfbff commit 3bc6eaf
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 85 deletions.
4 changes: 2 additions & 2 deletions examples/seeder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use color_eyre::{eyre::Report, Result};
use csv::Reader;
use dotenv::dotenv;
use entity::{
census, city, core_services, fargate_price, infrastructure, opportunity, people, prelude::*,
recreation, retail, speed_limit, summary, transit,
census, city, core_services, infrastructure, opportunity, people, prelude::*, recreation,
retail, speed_limit, summary, transit,
};
use sea_orm::{prelude::Uuid, ActiveValue, Database, EntityTrait};
use serde::Deserialize;
Expand Down
159 changes: 76 additions & 83 deletions lambdas/src/bin/price-fargate/get-price-fargate.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
use dotenv::dotenv;
use effortless::{
api::{extract_pagination_parameters, invalid_path_parameter, parse_query_string_parameter},
error::{APIError, APIErrors},
fragment::{get_apigw_request_id, BnaRequestExt},
api::{extract_pagination_parameters, invalid_path_parameter, invalid_query_parameter},
error::APIErrors,
fragment::BnaRequestExt,
};
use entity::prelude::*;
use lambda_http::{run, service_fn, Body, Error, IntoResponse, Request, Response};
use lambdas::{
api_database_connect, build_paginated_response,
core::resource::price::adaptor::get_price_fargate_adaptor, Context,
core::resource::price::{
adaptor::{get_price_fargate_adaptor, get_prices_fargate_adaptor},
PriceParameters,
},
Context, Sort,
};
use sea_orm::{EntityTrait, PaginatorTrait, QueryOrder, QuerySelect};
use serde_json::json;
use tracing::{debug, info};
use tracing::info;

async fn function_handler(event: Request) -> Result<Response<Body>, Error> {
dotenv().ok();
Expand All @@ -23,88 +23,81 @@ async fn function_handler(event: Request) -> Result<Response<Body>, Error> {
Err(e) => return Ok(e),
};

// Retrieve the ID of the entry to update.
let parameter = "id";
let id = event.path_parameter::<i32>(parameter);

// Set the database connection.
let db = match api_database_connect(&event).await {
Ok(db) => db,
Err(e) => return Ok(e),
};

// Retrieve all entries or a specific one.
debug!("Processing the requests...");
let res = match id {
Some(id) => match id {
Ok(id) => {
let ctx = Context::new(
event.apigw_request_id(),
event
.uri()
.path_and_query()
.expect("to have a path and optional query parameters")
.to_string(),
);
// info!("{:#?}", params);
match get_price_fargate_adaptor(id, ctx).await {
Ok(v) => return Ok(v.into_response().await),
Err(e) => return Ok(APIErrors::from(e).into()),
}
// Retrieve price parameter.
let mut price_parameters = PriceParameters::default();
let parameter = "sort";
let sort = event.query_string_parameter::<Sort>(parameter);
if let Some(sort) = sort {
match sort {
Ok(sort) => {
price_parameters.set_sort(Some(sort));
}
Err(e) => {
return Ok(
invalid_path_parameter(&event, parameter, e.to_string().as_str()).into(),
let api_error = invalid_query_parameter(
&event,
parameter,
format!("failed to process the `{parameter}` parameter: {e}").as_str(),
);
return Ok(APIErrors::new(&[api_error]).into());
}
},
None => {
// Retrieve the filter if any.
let latest: Option<bool> = match parse_query_string_parameter::<bool>(&event, "latest")
{
Ok(latest) => latest,
Err(e) => return Ok(e.into()),
};

// Select the entity.
let mut select = FargatePrice::find();
}
}

// Select latest only.
if latest.is_some() {
select = select
.order_by_asc(entity::fargate_price::Column::CreatedAt)
.limit(1);
let parameter = "latest";
let latest = event.query_string_parameter::<bool>(parameter);
if let Some(latest) = latest {
match latest {
Ok(latest) => {
price_parameters.set_latest(latest);
}
Err(e) => {
let api_error = invalid_query_parameter(
&event,
parameter,
format!("failed to process the `{parameter}` parameter: {e}").as_str(),
);
return Ok(APIErrors::new(&[api_error]).into());
}

// Select the results.
let query = select
.clone()
.paginate(&db, pagination.page_size())
.fetch_page(pagination.page)
.await;
let res: Response<Body> = match query {
Ok(models) => {
let total_items = select.count(&db).await?;
build_paginated_response(
json!(models),
total_items,
pagination.page,
pagination.page_size(),
&event,
)?
}
Err(e) => APIError::with_pointer(
get_apigw_request_id(&event),
event.uri().path().to_string().as_str(),
e.to_string().as_str(),
)
.into(),
};
res
}
};
}

// Retrieve the ID of the entry to retrieve.
let parameter = "id";
let id = event.path_parameter::<i32>(parameter);

Ok(res)
// Retrieve a specific entry if an id was specified.
if let Some(id) = id {
let id = match id {
Ok(id) => id,
Err(e) => {
let api_error = invalid_path_parameter(
&event,
parameter,
format!("failed to process the `{parameter}` parameter: {e}").as_str(),
);
return Ok(APIErrors::new(&[api_error]).into());
}
};
let ctx = Context::new(
event.apigw_request_id(),
event
.uri()
.path_and_query()
.expect("to have a path and optional query parameters")
.to_string(),
);
match get_price_fargate_adaptor(id, ctx).await {
Ok(v) => return Ok(v.into_response().await),
Err(e) => return Ok(APIErrors::from(e).into()),
};
}
// Retrieve all entries.
match get_prices_fargate_adaptor(price_parameters, pagination.page, pagination.page_size())
.await
{
Ok(v) => Ok(v.payload().into_response().await),
Err(e) => Ok(APIErrors::from(e).into()),
}
}

#[tokio::main]
Expand Down
14 changes: 14 additions & 0 deletions lambdas/src/core/resource/price/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ pub struct PriceParameters {
latest: bool,
}

impl PriceParameters {
pub fn new(sort: Option<Sort>, latest: bool) -> Self {
Self { sort, latest }
}

pub fn set_sort(&mut self, sort: Option<Sort>) {
self.sort = sort;
}

pub fn set_latest(&mut self, latest: bool) {
self.latest = latest;
}
}

impl Default for PriceParameters {
fn default() -> Self {
Self {
Expand Down
3 changes: 3 additions & 0 deletions lambdas/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use lambda_http::{
use sea_orm::{Database, DatabaseConnection, DbErr};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use serde_plain::derive_fromstr_from_deserialize;
use std::env;
use tracing::{debug, error};

Expand Down Expand Up @@ -494,6 +495,8 @@ pub enum Sort {
Desc,
}

derive_fromstr_from_deserialize!(Sort);

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 3bc6eaf

Please sign in to comment.