less verbose logger

This commit is contained in:
2019-11-07 21:05:39 +01:00
parent 51cc6c4765
commit b5010539bb
2 changed files with 59 additions and 52 deletions

View File

@@ -12,6 +12,14 @@ pub struct BuySellParams {
global_mod: Option<f64>, global_mod: Option<f64>,
} }
#[derive(Serialize, Deserialize, Debug)]
pub struct NewGroupLoot {
source_name: String,
pub items: Vec<db::Item>,
}
/// A generic response for all queries /// A generic response for all queries
#[derive(Serialize, Debug, Default)] #[derive(Serialize, Debug, Default)]
pub struct ApiResponse { pub struct ApiResponse {
@@ -74,7 +82,7 @@ pub enum ApiActions {
UnclaimItem(i32, i32), UnclaimItem(i32, i32),
UndoLastAction(i32), UndoLastAction(i32),
// Group level // Group level
AddLoot(Vec<db::Item>), AddLoot(NewGroupLoot),
// Admin level // Admin level
//AddPlayer(String, f64), //AddPlayer(String, f64),
//AddInventoryItem(pub String, pub i32), //AddInventoryItem(pub String, pub i32),
@@ -233,9 +241,9 @@ pub fn execute(
None None
} }
// Group actions // Group actions
ApiActions::AddLoot(items) => { ApiActions::AddLoot(data) => {
let mut added_items = 0; let mut added_items = 0;
for item in items.into_iter() { for item in data.items.into_iter() {
if let Ok(added) = db::LootManager(conn, 0).add_from(&item) { if let Ok(added) = db::LootManager(conn, 0).add_from(&item) {
response.push_update(added); response.push_update(added);
added_items += 1; added_items += 1;

View File

@@ -1,31 +1,28 @@
use actix_cors::Cors; use actix_cors::Cors;
use actix_files as fs; use actix_files as fs;
use actix_web::{web, middleware, App, Error, HttpResponse, HttpServer, Either}; use actix_web::{middleware, web, App, Either, Error, HttpResponse, HttpServer};
use futures::{Future}; use futures::Future;
use std::env; use std::env;
use lootalot_db as db;
use crate::api; use crate::api;
use lootalot_db as db;
type AppPool = web::Data<db::Pool>; type AppPool = web::Data<db::Pool>;
type PlayerId = web::Path<i32>; type PlayerId = web::Path<i32>;
type ItemId = web::Json<i32>; type ItemId = web::Json<i32>;
type IdList = web::Json<api::IdList>; type IdList = web::Json<api::IdList>;
type BuySellParams = web::Json<api::BuySellParams>;
type NewGroupLoot = web::Json<api::NewGroupLoot>;
#[derive(Serialize, Deserialize, Debug)] type MaybeForbidden =
struct NewGroupLoot { actix_web::Either<Box<dyn Future<Item = HttpResponse, Error = Error>>, HttpResponse>;
source_name: String,
items: Vec<db::Item>,
}
type MaybeForbidden = actix_web::Either<Box<dyn Future<Item = HttpResponse, Error = Error>>, HttpResponse>;
/// Wraps call to the database query and convert its result as a async HttpResponse /// Wraps call to the database query and convert its result as a async HttpResponse
fn db_call( fn db_call(
pool: AppPool, pool: AppPool,
query: api::ApiActions, query: api::ApiActions,
) -> impl Future<Item = HttpResponse, Error = Error> ) -> impl Future<Item = HttpResponse, Error = Error> {
{
let conn = pool.get().unwrap(); let conn = pool.get().unwrap();
web::block(move || api::execute(&conn, query)).then(|res| match res { web::block(move || api::execute(&conn, query)).then(|res| match res {
Ok(r) => HttpResponse::Ok().json(r), Ok(r) => HttpResponse::Ok().json(r),
@@ -42,7 +39,6 @@ fn restricted_to_group(id: i32, params: (AppPool, api::ApiActions)) -> MaybeForb
} else { } else {
Either::A(Box::new(db_call(params.0, params.1))) Either::A(Box::new(db_call(params.0, params.1)))
} }
} }
fn configure_api(config: &mut web::ServiceConfig) { fn configure_api(config: &mut web::ServiceConfig) {
@@ -52,26 +48,30 @@ fn configure_api(config: &mut web::ServiceConfig) {
.service( .service(
web::scope("/players") web::scope("/players")
.service( .service(
web::resource("/").route( web::resource("/")
web::get().to_async(|pool| db_call(pool, Q::FetchPlayers)), .route(web::get().to_async(|pool| db_call(pool, Q::FetchPlayers))), //.route(web::post().to_async(endpoints::new_player))
), //.route(web::post().to_async(endpoints::new_player))
) // List of players ) // List of players
.service( .service(
web::scope("/{player_id}") web::scope("/{player_id}")
.route("/", web::get().to_async(|pool, player: PlayerId| { .route(
db_call(pool, Q::FetchPlayer(*player)) "/",
})) web::get().to_async(|pool, player: PlayerId| {
.route("/notifications", web::get().to_async(|pool, player: PlayerId| { db_call(pool, Q::FetchPlayer(*player))
db_call(pool, Q::FetchNotifications(*player)) }),
})) )
.route(
"/notifications",
web::get().to_async(|pool, player: PlayerId| {
db_call(pool, Q::FetchNotifications(*player))
}),
)
.service( .service(
web::resource("/claims") web::resource("/claims")
//.route(web::get().to_async(endpoints::player_claims)) //.route(web::get().to_async(endpoints::player_claims))
.route(web::post().to_async( .route(web::post().to_async(
|pool, (player, data): (PlayerId, IdList)| |pool, (player, data): (PlayerId, IdList)| {
{ db_call(pool, Q::ClaimItems(*player, data.into_inner()))
db_call(pool, Q::ClaimItems(*player, data.clone())) },
}
)) ))
.route(web::put().to_async( .route(web::put().to_async(
|pool, (player, data): (PlayerId, ItemId)| { |pool, (player, data): (PlayerId, ItemId)| {
@@ -80,10 +80,7 @@ fn configure_api(config: &mut web::ServiceConfig) {
)) ))
.route(web::delete().to_async( .route(web::delete().to_async(
|pool, (player, data): (PlayerId, ItemId)| { |pool, (player, data): (PlayerId, ItemId)| {
db_call( db_call(pool, Q::UnclaimItem(*player, *data))
pool,
Q::UnclaimItem(*player, *data),
)
}, },
)), )),
) )
@@ -92,10 +89,7 @@ fn configure_api(config: &mut web::ServiceConfig) {
//.route(web::get().to_async(...)) //.route(web::get().to_async(...))
.route(web::put().to_async( .route(web::put().to_async(
|pool, (player, data): (PlayerId, web::Json<f64>)| { |pool, (player, data): (PlayerId, web::Json<f64>)| {
db_call( db_call(pool, Q::UpdateWealth(*player, *data))
pool,
Q::UpdateWealth(*player, *data),
)
}, },
)), )),
) )
@@ -105,35 +99,39 @@ fn configure_api(config: &mut web::ServiceConfig) {
db_call(pool, Q::FetchLoot(*player)) db_call(pool, Q::FetchLoot(*player))
})) }))
.route(web::put().to_async( .route(web::put().to_async(
move |pool, (player, data): (PlayerId, web::Json<api::BuySellParams>)| { move |pool, (player, data): (PlayerId, BuySellParams)| {
db_call(pool, Q::BuyItems(*player, data.into_inner())) db_call(pool, Q::BuyItems(*player, data.into_inner()))
}, },
)) ))
.route(web::post().to( .route(web::post().to(
move |pool, (player, data): (PlayerId, web::Json<NewGroupLoot>)| { move |pool, (player, data): (PlayerId, NewGroupLoot)| {
restricted_to_group(*player, (pool, Q::AddLoot(data.into_inner().items))) restricted_to_group(
*player,
(pool, Q::AddLoot(data.into_inner())),
)
}, },
)) ))
.route(web::delete().to_async( .route(web::delete().to_async(
move |pool, (player, data): (PlayerId, web::Json<api::BuySellParams>)| { move |pool, (player, data): (PlayerId, BuySellParams)| {
db_call(pool, Q::SellItems(*player, data.into_inner())) db_call(pool, Q::SellItems(*player, data.into_inner()))
}, },
)), )),
) )
.service( .service(web::scope("/events").route(
web::scope("/events") "/last",
.route("/last", web::delete().to_async(|pool, player: PlayerId| { web::delete().to_async(|pool, player: PlayerId| {
db_call(pool, Q::UndoLastAction(*player)) db_call(pool, Q::UndoLastAction(*player))
})) }),
) )),
), ),
) )
.route("/claims", web::get().to_async(|pool| db_call(pool, Q::FetchClaims))) .route(
"/claims",
web::get().to_async(|pool| db_call(pool, Q::FetchClaims)),
)
.route( .route(
"/items", "/items",
web::get() web::get().to_async(move |pool: AppPool| db_call(pool, Q::FetchInventory)),
.to_async(move |pool: AppPool| db_call(pool, Q::FetchInventory)),
), ),
); );
} }
@@ -153,7 +151,8 @@ pub fn serve() -> std::io::Result<()> {
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"]) .allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
.max_age(3600), .max_age(3600),
) )
.wrap(middleware::Logger::default()) //.wrap(middleware::Logger::default())
.wrap(middleware::Logger::new("%r -> %s (%{User-Agent}i)"))
.service(fs::Files::new("/", www_root.clone()).index_file("index.html")) .service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
}) })
.bind("127.0.0.1:8088")? .bind("127.0.0.1:8088")?