fixes errors, cleans up
This commit is contained in:
@@ -33,8 +33,7 @@ pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
|||||||
pub type ActionResult<R> = Result<R, diesel::result::Error>;
|
pub type ActionResult<R> = Result<R, diesel::result::Error>;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
enum Update {
|
pub enum Update {
|
||||||
NoUpdate,
|
|
||||||
Wealth(Wealth),
|
Wealth(Wealth),
|
||||||
ItemAdded(Item),
|
ItemAdded(Item),
|
||||||
ItemRemoved(Item),
|
ItemRemoved(Item),
|
||||||
@@ -43,7 +42,7 @@ enum Update {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
enum Value {
|
pub enum Value {
|
||||||
Item(Item),
|
Item(Item),
|
||||||
Claim(Claim),
|
Claim(Claim),
|
||||||
ItemList(Vec<Item>),
|
ItemList(Vec<Item>),
|
||||||
@@ -53,10 +52,10 @@ enum Value {
|
|||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Default)]
|
#[derive(Serialize, Deserialize, Debug, Default)]
|
||||||
pub struct ApiResponse {
|
pub struct ApiResponse {
|
||||||
pub value: Option<Value>, // The value requested, if any
|
pub value: Option<Value>, // The value requested, if any
|
||||||
pub notify: Option<String>, // A text to notify user, if relevant
|
pub notify: Option<String>, // A text to notify user, if relevant
|
||||||
pub updates: Option<Vec<Update>>, // A list of updates, if any
|
pub updates: Option<Vec<Update>>, // A list of updates, if any
|
||||||
pub errors: Option<String>, // A text describing errors, if any
|
pub errors: Option<String>, // A text describing errors, if any
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ApiResponse {
|
impl ApiResponse {
|
||||||
@@ -68,6 +67,14 @@ impl ApiResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn push_error<S: Into<String>>(&mut self, error: S) {
|
||||||
|
if let Some(errors) = self.errors.as_mut() {
|
||||||
|
*errors = format!("{}\n{}", errors, error.into());
|
||||||
|
} else {
|
||||||
|
self.errors = Some(error.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn set_value(&mut self, value: Value) {
|
fn set_value(&mut self, value: Value) {
|
||||||
self.value = Some(value);
|
self.value = Some(value);
|
||||||
}
|
}
|
||||||
@@ -77,24 +84,23 @@ impl ApiResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
pub enum ApiError {
|
pub enum ApiError {
|
||||||
DieselError(diesel::result::Error),
|
DieselError(diesel::result::Error),
|
||||||
InvalidAction(String),
|
InvalidAction(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum ApiActions<'a> {
|
pub enum ApiActions {
|
||||||
FetchPlayers,
|
FetchPlayers,
|
||||||
FetchInventory,
|
FetchInventory,
|
||||||
// Player actions
|
// Player actions
|
||||||
FetchLoot(i32),
|
FetchLoot(i32),
|
||||||
UpdateWealth(i32, f32),
|
UpdateWealth(i32, f32),
|
||||||
BuyItems(i32, &'a Vec<(i32, Option<f32>)>),
|
BuyItems(i32, Vec<(i32, Option<f32>)>),
|
||||||
SellItems(i32, &'a Vec<(i32, Option<f32>)>),
|
SellItems(i32, Vec<(i32, Option<f32>)>),
|
||||||
ClaimItem(i32, i32),
|
ClaimItem(i32, i32),
|
||||||
UnclaimItem(i32, i32),
|
UnclaimItem(i32, i32),
|
||||||
// Group actions
|
// Group actions
|
||||||
AddLoot(&'a Vec<Item>),
|
AddLoot(Vec<Item>),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum AdminActions {
|
pub enum AdminActions {
|
||||||
@@ -104,38 +110,26 @@ pub enum AdminActions {
|
|||||||
//SetClaimsTimeout(pub i32),
|
//SetClaimsTimeout(pub i32),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn execute(
|
||||||
pub fn execute<'a>(pool: Pool, query: ApiActions<'a>) -> Result<ApiResponse, diesel::result::Error> {
|
conn: &DbConnection,
|
||||||
let conn = pool.get().map_err(|e| {dbg!(e); diesel::result::Error::NotFound })?;
|
query: ApiActions,
|
||||||
|
) -> Result<ApiResponse, diesel::result::Error> {
|
||||||
let mut response = ApiResponse::default();
|
let mut response = ApiResponse::default();
|
||||||
match query {
|
match query {
|
||||||
ApiActions::FetchPlayers => {
|
ApiActions::FetchPlayers => {
|
||||||
response.set_value(
|
response.set_value(Value::PlayerList(models::player::Players(conn).all()?));
|
||||||
Value::PlayerList(
|
}
|
||||||
schema::players::table.load::<models::Player>(conn)?
|
|
||||||
)
|
|
||||||
);
|
|
||||||
},
|
|
||||||
ApiActions::FetchInventory => {
|
ApiActions::FetchInventory => {
|
||||||
response.set_value(
|
response.set_value(Value::ItemList(models::item::Inventory(conn).all()?));
|
||||||
Value::ItemList(
|
|
||||||
models::item::Inventory(conn).all()?));
|
|
||||||
}
|
}
|
||||||
ApiActions::FetchLoot(id) => {
|
ApiActions::FetchLoot(id) => {
|
||||||
response.set_value(
|
response.set_value(Value::ItemList(models::item::LootManager(conn, id).all()?));
|
||||||
Value::ItemList(
|
}
|
||||||
models::item::LootManager(conn, id).all()?
|
|
||||||
)
|
|
||||||
);
|
|
||||||
},
|
|
||||||
ApiActions::UpdateWealth(id, amount) => {
|
ApiActions::UpdateWealth(id, amount) => {
|
||||||
response.push_update(
|
response.push_update(Update::Wealth(
|
||||||
Update::Wealth(
|
models::player::AsPlayer(conn, id).update_wealth(amount)?,
|
||||||
models::player::AsPlayer(conn, id)
|
));
|
||||||
.update_wealth(amount)?
|
}
|
||||||
)
|
|
||||||
);
|
|
||||||
},
|
|
||||||
ApiActions::BuyItems(id, params) => {
|
ApiActions::BuyItems(id, params) => {
|
||||||
let mut cumulated_diff: Vec<Wealth> = Vec::with_capacity(params.len());
|
let mut cumulated_diff: Vec<Wealth> = Vec::with_capacity(params.len());
|
||||||
let mut added_items: Vec<models::Item> = Vec::with_capacity(params.len());
|
let mut added_items: Vec<models::Item> = Vec::with_capacity(params.len());
|
||||||
@@ -143,7 +137,7 @@ pub fn execute<'a>(pool: Pool, query: ApiActions<'a>) -> Result<ApiResponse, die
|
|||||||
// Use a transaction to avoid incoherant state in case of error
|
// Use a transaction to avoid incoherant state in case of error
|
||||||
if let Ok((item, diff)) = conn.transaction(|| {
|
if let Ok((item, diff)) = conn.transaction(|| {
|
||||||
// Find item in inventory
|
// Find item in inventory
|
||||||
let item = models::item::Inventory(conn).find(*item_id)?;
|
let item = models::item::Inventory(conn).find(item_id)?;
|
||||||
let new_item = models::item::LootManager(conn, id).add_from(&item)?;
|
let new_item = models::item::LootManager(conn, id).add_from(&item)?;
|
||||||
let sell_price = match price_mod {
|
let sell_price = match price_mod {
|
||||||
Some(modifier) => item.base_price as f32 * modifier,
|
Some(modifier) => item.base_price as f32 * modifier,
|
||||||
@@ -156,134 +150,92 @@ pub fn execute<'a>(pool: Pool, query: ApiActions<'a>) -> Result<ApiResponse, die
|
|||||||
cumulated_diff.push(diff);
|
cumulated_diff.push(diff);
|
||||||
response.push_update(Update::ItemAdded(item));
|
response.push_update(Update::ItemAdded(item));
|
||||||
} else {
|
} else {
|
||||||
response.errors = Some(format!("Error adding {}", item_id));
|
response.push_error(format!("Error adding {}", item_id));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let all_diff = cumulated_diff.into_iter().fold(Wealth::from_gp(0.0), |sum, diff|
|
let all_diff = cumulated_diff
|
||||||
Wealth {
|
.into_iter()
|
||||||
|
.fold(Wealth::from_gp(0.0), |sum, diff| Wealth {
|
||||||
cp: sum.cp + diff.cp,
|
cp: sum.cp + diff.cp,
|
||||||
sp: sum.sp + diff.sp,
|
sp: sum.sp + diff.sp,
|
||||||
gp: sum.gp + diff.gp,
|
gp: sum.gp + diff.gp,
|
||||||
pp: sum.pp + diff.pp,
|
pp: sum.pp + diff.pp,
|
||||||
}
|
});
|
||||||
);
|
|
||||||
response.push_update(Update::Wealth(all_diff));
|
response.push_update(Update::Wealth(all_diff));
|
||||||
},
|
}
|
||||||
ApiActions::SellItems(id, params) => {
|
ApiActions::SellItems(id, params) => {
|
||||||
sell(conn, id, params, &mut response);
|
let mut all_results: Vec<Wealth> = Vec::with_capacity(params.len());
|
||||||
},
|
for (loot_id, price_mod) in params.into_iter() {
|
||||||
|
let res = conn.transaction(|| {
|
||||||
|
let deleted = models::item::LootManager(conn, id).remove(loot_id)?;
|
||||||
|
let mut sell_value = deleted.base_price as f32 / 2.0;
|
||||||
|
if let Some(modifier) = price_mod {
|
||||||
|
sell_value *= modifier;
|
||||||
|
}
|
||||||
|
models::player::AsPlayer(conn, id)
|
||||||
|
.update_wealth(sell_value)
|
||||||
|
.map(|diff| (deleted, diff))
|
||||||
|
});
|
||||||
|
if let Ok((deleted, diff)) = res {
|
||||||
|
all_results.push(diff);
|
||||||
|
response.push_update(Update::ItemRemoved(deleted));
|
||||||
|
} else {
|
||||||
|
response.push_error(format!("Error selling {}", loot_id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let wealth = all_results
|
||||||
|
.into_iter()
|
||||||
|
.fold(Wealth::from_gp(0.0), |sum, diff| Wealth {
|
||||||
|
cp: sum.cp + diff.cp,
|
||||||
|
sp: sum.sp + diff.sp,
|
||||||
|
gp: sum.gp + diff.gp,
|
||||||
|
pp: sum.pp + diff.pp,
|
||||||
|
});
|
||||||
|
response.push_update(Update::Wealth(wealth));
|
||||||
|
}
|
||||||
ApiActions::ClaimItem(id, item) => {
|
ApiActions::ClaimItem(id, item) => {
|
||||||
response.push_update(
|
response.push_update(Update::ClaimAdded(
|
||||||
Update::ClaimAdded(
|
models::claim::Claims(conn).add(id, item)?,
|
||||||
models::claim::Claims(conn)
|
));
|
||||||
.add(id, item)?
|
}
|
||||||
)
|
|
||||||
);
|
|
||||||
},
|
|
||||||
ApiActions::UnclaimItem(id, item) => {
|
ApiActions::UnclaimItem(id, item) => {
|
||||||
response.push_update(
|
response.push_update(Update::ClaimRemoved(
|
||||||
Update::ClaimRemoved(
|
models::claim::Claims(conn).remove(id, item)?,
|
||||||
models::claim::Claims(conn)
|
));
|
||||||
.remove(id, item)?
|
}
|
||||||
)
|
|
||||||
);
|
|
||||||
},
|
|
||||||
// Group actions
|
// Group actions
|
||||||
ApiActions::AddLoot(items) => {},
|
ApiActions::AddLoot(items) => {}
|
||||||
}
|
}
|
||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch all existing claims
|
/// Fetch all existing claims
|
||||||
pub fn fetch_claims(conn: &DbConnection) -> QueryResult<Vec<models::Claim>> {
|
pub fn fetch_claims(conn: &DbConnection) -> QueryResult<Vec<models::Claim>> {
|
||||||
schema::claims::table.load::<models::Claim>(conn)
|
schema::claims::table.load::<models::Claim>(conn)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sell a set of items from this player chest
|
/// Resolve all pending claims and dispatch claimed items.
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// When a player gets an item, it's debt is increased by this item sell value
|
||||||
/// Result containing the difference in coins after operation
|
pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
|
||||||
pub fn sell(
|
let data = models::claim::Claims(conn).grouped_by_item()?;
|
||||||
conn: &DbConnection,
|
dbg!(&data);
|
||||||
id: i32,
|
|
||||||
params: &Vec<(i32, Option<f32>)>,
|
for (item, claims) in data {
|
||||||
response: &mut ApiResponse,
|
match claims.len() {
|
||||||
) {
|
1 => {
|
||||||
let mut all_results: Vec<Wealth> = Vec::with_capacity(params.len());
|
let claim = claims.get(0).unwrap();
|
||||||
for (loot_id, price_mod) in params.into_iter() {
|
let player_id = claim.player_id;
|
||||||
let res = conn.transaction(|| {
|
conn.transaction(|| {
|
||||||
let deleted = models::item::LootManager(conn, id).remove(*loot_id)?;
|
claim.resolve_claim(conn)?;
|
||||||
let mut sell_value = deleted.base_price as f32 / 2.0;
|
//models::item::LootManager(self.0, 0).set_owner(claim.loot_id, claim.player_id)?;
|
||||||
if let Some(modifier) = price_mod {
|
models::player::AsPlayer(conn, player_id).update_debt(item.sell_value())
|
||||||
sell_value *= modifier;
|
})?;
|
||||||
}
|
|
||||||
models::player::AsPlayer(conn, id)
|
|
||||||
.update_wealth(sell_value)
|
|
||||||
.map(|diff| (deleted, diff))
|
|
||||||
});
|
|
||||||
if let Ok((deleted, diff)) = res {
|
|
||||||
all_results.push(diff);
|
|
||||||
response.push_update(
|
|
||||||
Update::ItemRemoved(deleted)
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
response.errors = Some(format!("Error selling {}", loot_id));
|
|
||||||
}
|
}
|
||||||
|
_ => (),
|
||||||
}
|
}
|
||||||
let wealth = all_results.into_iter().fold(Wealth::from_gp(0.0), |sum, diff| {
|
|
||||||
Wealth {
|
|
||||||
cp: sum.cp + diff.cp,
|
|
||||||
sp: sum.sp + diff.sp,
|
|
||||||
gp: sum.gp + diff.gp,
|
|
||||||
pp: sum.pp + diff.pp,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
response.push_update(Update::Wealth(wealth));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wrapper for interactions of admins with the DB.
|
|
||||||
pub struct AsAdmin<'q>(&'q DbConnection);
|
|
||||||
|
|
||||||
impl<'q> AsAdmin<'q> {
|
|
||||||
/// Adds a player to the database
|
|
||||||
///
|
|
||||||
/// Takes the player name and starting wealth (in gold value).
|
|
||||||
pub fn add_player(self, name: &str, start_wealth: f32) -> ActionResult<()> {
|
|
||||||
models::player::Players(self.0).add(name, start_wealth)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds a list of items to the group loot
|
|
||||||
pub fn add_loot(self, items: Vec<models::item::Item>) -> ActionResult<()> {
|
|
||||||
for item_desc in items.iter() {
|
|
||||||
models::item::LootManager(self.0, 0).add_from(item_desc)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolve all pending claims and dispatch claimed items.
|
|
||||||
///
|
|
||||||
/// When a player gets an item, it's debt is increased by this item sell value
|
|
||||||
pub fn resolve_claims(self) -> ActionResult<()> {
|
|
||||||
let data = models::claim::Claims(self.0).grouped_by_item()?;
|
|
||||||
dbg!(&data);
|
|
||||||
|
|
||||||
for (item, claims) in data {
|
|
||||||
match claims.len() {
|
|
||||||
1 => {
|
|
||||||
let claim = claims.get(0).unwrap();
|
|
||||||
let player_id = claim.player_id;
|
|
||||||
self.0.transaction(|| {
|
|
||||||
claim.resolve_claim(self.0)?;
|
|
||||||
//models::item::LootManager(self.0, 0).set_owner(claim.loot_id, claim.player_id)?;
|
|
||||||
models::player::AsPlayer(self.0, player_id).update_debt(item.sell_value())
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets up a connection pool and returns it.
|
/// Sets up a connection pool and returns it.
|
||||||
|
|||||||
302
src/server.rs
302
src/server.rs
@@ -1,44 +1,24 @@
|
|||||||
use actix_cors::Cors;
|
use actix_cors::Cors;
|
||||||
use actix_files as fs;
|
use actix_files as fs;
|
||||||
use actix_web::{web, App, Error, HttpResponse, HttpServer};
|
use actix_web::{web, middleware, App, Error, HttpResponse, HttpServer};
|
||||||
use futures::Future;
|
use futures::Future;
|
||||||
use lootalot_db::{DbApi, Pool, QueryResult};
|
|
||||||
use lootalot_db::{Item, LootManager};
|
|
||||||
use lootalot_db as db;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::default;
|
|
||||||
|
|
||||||
type AppPool = web::Data<Pool>;
|
use lootalot_db as db;
|
||||||
|
|
||||||
/// Wraps call to the DbApi and process its result as a async HttpResponse
|
type AppPool = web::Data<db::Pool>;
|
||||||
///
|
type PlayerId = web::Path<i32>;
|
||||||
/// Provides a convenient way to call the api inside a route definition. Given a connection pool,
|
type ItemId = web::Json<i32>;
|
||||||
/// access to the api is granted in a closure. The closure is called in a blocking way and should
|
type ItemListWithMods = web::Json<Vec<(i32, Option<f32>)>>;
|
||||||
/// return a QueryResult.
|
|
||||||
/// If the query succeeds, it's result is returned as JSON data. Otherwise, an InternalServerError
|
/// Wraps call to the database query and convert its result as a async HttpResponse
|
||||||
/// is returned.
|
pub fn db_call(
|
||||||
///
|
pool: AppPool,
|
||||||
/// # Usage
|
query: db::ApiActions,
|
||||||
/// ```
|
) -> impl Future<Item = HttpResponse, Error = Error>
|
||||||
/// (...)
|
|
||||||
/// .route("path/to/",
|
|
||||||
/// move |pool: web::Data<Pool>| {
|
|
||||||
/// // user data can be processed here
|
|
||||||
/// // ...
|
|
||||||
/// db_call(pool, move |api| {
|
|
||||||
/// // ...do what you want with the api
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// )
|
|
||||||
/// ```
|
|
||||||
pub fn db_call<J, Q>(pool: AppPool, query: Q) -> impl Future<Item = HttpResponse, Error = Error>
|
|
||||||
where
|
|
||||||
J: serde::ser::Serialize + Send + 'static,
|
|
||||||
Q: Fn(DbConnection) -> ApiResponse<J> + Send + 'static,
|
|
||||||
{
|
{
|
||||||
let conn = pool.get().unwrap();
|
let conn = pool.get().unwrap();
|
||||||
web::block(move || query(conn)).then(|res| match res {
|
web::block(move || db::execute(&conn, query)).then(|res| match res {
|
||||||
Ok(r) => HttpResponse::Ok().json(r),
|
Ok(r) => HttpResponse::Ok().json(r),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
dbg!(&e);
|
dbg!(&e);
|
||||||
@@ -47,205 +27,91 @@ where
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
mod endpoints {
|
fn configure_app(config: &mut web::ServiceConfig) {
|
||||||
|
config.service(
|
||||||
use super::*;
|
web::scope("/api")
|
||||||
|
.service(
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
web::scope("/players")
|
||||||
pub struct PlayerClaim {
|
.service(
|
||||||
player_id: i32,
|
web::resource("/").route(
|
||||||
item_id: i32,
|
web::get().to_async(|pool| db_call(pool, db::ApiActions::FetchPlayers)),
|
||||||
}
|
), //.route(web::post().to_async(endpoints::new_player))
|
||||||
|
) // List of players
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
.service(
|
||||||
pub struct WealthUpdate {
|
web::scope("/{player_id}")
|
||||||
player_id: i32,
|
//.route(web::get().to_async(...)) // Details of player
|
||||||
value_in_gp: f32,
|
.service(
|
||||||
}
|
web::resource("/claims")
|
||||||
|
//.route(web::get().to_async(endpoints::player_claims))
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
.route(web::put().to_async(
|
||||||
pub struct NewPlayer {
|
|pool, (player, data): (PlayerId, ItemId)| {
|
||||||
pub name: String,
|
db_call(pool, db::ApiActions::ClaimItem(*player, *data))
|
||||||
pub wealth: f32,
|
},
|
||||||
}
|
))
|
||||||
|
.route(web::delete().to_async(
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
|pool, (player, data): (PlayerId, ItemId)| {
|
||||||
pub struct LootUpdate {
|
db_call(
|
||||||
player_id: i32,
|
pool,
|
||||||
items: Vec<(i32, Option<f32>)>,
|
db::ApiActions::UnclaimItem(*player, *data),
|
||||||
}
|
)
|
||||||
|
},
|
||||||
pub fn players_list(pool: AppPool) -> impl Future<Item = HttpResponse, Error = Error> {
|
)),
|
||||||
db_call(pool, move |conn| {
|
)
|
||||||
let (value, errors) = match db::Players(conn).all() {
|
.service(
|
||||||
Ok(v) => (Some(v), None),
|
web::resource("/wealth")
|
||||||
Err(e) => (None, Some(e.to_string())),
|
//.route(web::get().to_async(...))
|
||||||
};
|
.route(web::put().to_async(
|
||||||
ApiResponse {
|
|pool, (player, data): (PlayerId, web::Json<f32>)| {
|
||||||
value,
|
db_call(
|
||||||
errors,
|
pool,
|
||||||
..Default::default()
|
db::ApiActions::UpdateWealth(*player, *data),
|
||||||
}
|
)
|
||||||
})
|
},
|
||||||
}
|
)),
|
||||||
|
)
|
||||||
pub fn player_loot(
|
.service(
|
||||||
pool: AppPool,
|
web::resource("/loot")
|
||||||
player_id: web::Path<i32>,
|
.route(web::get().to_async(|pool, player: PlayerId| {
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
db_call(pool, db::ApiActions::FetchLoot(*player))
|
||||||
db_call(pool, move |conn| {
|
}))
|
||||||
let (value, errors) = {
|
.route(web::put().to_async(
|
||||||
match db::LootManager(&conn, *player_id).all() {
|
move |pool, (player, data): (PlayerId, ItemListWithMods)| {
|
||||||
Ok(v) => (Some(v), None),
|
db_call(pool, db::ApiActions::BuyItems(*player, data.into_inner()))
|
||||||
Err(e) => (None, Some(e.to_string())),
|
},
|
||||||
}
|
))
|
||||||
};
|
.route(web::delete().to_async(
|
||||||
ApiResponse {
|
move |pool, (player, data): (PlayerId, ItemListWithMods)| {
|
||||||
value,
|
db_call(pool, db::ApiActions::SellItems(*player, data.into_inner()))
|
||||||
errors,
|
},
|
||||||
..Default::default()
|
)),
|
||||||
}
|
),
|
||||||
})
|
),
|
||||||
}
|
)
|
||||||
|
//.route("/claims", web::get().to_async(endpoints::player_claims))
|
||||||
pub fn update_wealth(
|
.route(
|
||||||
pool: AppPool,
|
"/items",
|
||||||
(player, data): (web::Path<i32>, web::Json<WealthUpdate>),
|
web::get()
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
.to_async(move |pool: AppPool| db_call(pool, db::ApiActions::FetchInventory)),
|
||||||
db_call(pool, move |conn| {
|
),
|
||||||
let (updates, errors) =
|
);
|
||||||
match db::AsPlayer(conn, player)
|
|
||||||
.update_wealth(data.value_in_gp) {
|
|
||||||
Ok(w) => (Some(vec![w.as_tuple(),]), None),
|
|
||||||
Err(e) => (None, Some(e.to_string())),
|
|
||||||
};
|
|
||||||
ApiResponse {
|
|
||||||
updates,
|
|
||||||
errors,
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn buy_item(
|
|
||||||
pool: AppPool,
|
|
||||||
data: web::Json<LootUpdate>,
|
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
|
||||||
db_call(pool, move |api| {
|
|
||||||
api.as_player(data.player_id).buy(&data.items)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn sell_item(
|
|
||||||
pool: AppPool,
|
|
||||||
data: web::Json<LootUpdate>,
|
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
|
||||||
db_call(pool, move |api| {
|
|
||||||
api.as_player(data.player_id).sell(&data.items)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
pub fn player_claims(pool: AppPool) -> impl Future<Item = HttpResponse, Error = Error> {
|
|
||||||
db_call(pool, move |api| api.fetch_claims())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn put_claim(
|
|
||||||
pool: AppPool,
|
|
||||||
(player, loot): (web::Path<i32>, web::Json<PlayerClaim>),
|
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
|
||||||
db_call(pool, move |api| api.as_player(*player).claim(loot.item_id))
|
|
||||||
}
|
|
||||||
pub fn delete_claim(
|
|
||||||
pool: AppPool,
|
|
||||||
(player, data): (web::Path<i32>, web::Json<PlayerClaim>),
|
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
|
||||||
db_call(pool, move |api| {
|
|
||||||
api.as_player(*player).unclaim(data.item_id)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn serve() -> std::io::Result<()> {
|
pub fn serve() -> std::io::Result<()> {
|
||||||
let www_root: String = env::var("WWW_ROOT").expect("WWW_ROOT must be set");
|
let www_root: String = env::var("WWW_ROOT").expect("WWW_ROOT must be set");
|
||||||
|
let pool = db::create_pool();
|
||||||
dbg!(&www_root);
|
dbg!(&www_root);
|
||||||
let pool = lootalot_db::create_pool();
|
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.data(pool.clone())
|
.data(pool.clone())
|
||||||
|
.configure(configure_app)
|
||||||
.wrap(
|
.wrap(
|
||||||
Cors::new()
|
Cors::new()
|
||||||
.allowed_origin("http://localhost:8080")
|
.allowed_origin("http://localhost:8080")
|
||||||
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
|
||||||
.max_age(3600),
|
.max_age(3600),
|
||||||
)
|
)
|
||||||
.service(
|
.wrap(middleware::Logger::default())
|
||||||
web::scope("/api")
|
|
||||||
.service(
|
|
||||||
web::scope("/players")
|
|
||||||
.service(
|
|
||||||
web::resource("/")
|
|
||||||
.route(web::get().to_async(endpoints::players_list)),
|
|
||||||
) // List of players
|
|
||||||
//.route(web::put().to_async(endpoints::new_player)) // Create/Update player
|
|
||||||
.service(
|
|
||||||
web::scope("/{player_id}")
|
|
||||||
//.route(web::get().to_async(...)) // Details of player
|
|
||||||
.service(
|
|
||||||
web::resource("/claims")
|
|
||||||
//.route(web::get().to_async(endpoints::player_claims))
|
|
||||||
.route(web::put().to_async(endpoints::put_claim))
|
|
||||||
.route(web::delete().to_async(endpoints::delete_claim)),
|
|
||||||
)
|
|
||||||
.service(
|
|
||||||
web::resource("/wealth")
|
|
||||||
//.route(web::get().to_async(...))
|
|
||||||
.route(web::put().to_async(endpoints::update_wealth)),
|
|
||||||
)
|
|
||||||
.service(
|
|
||||||
web::resource("/loot")
|
|
||||||
.route(web::get().to_async(endpoints::player_loot))
|
|
||||||
.route(web::put().to_async(endpoints::buy_item))
|
|
||||||
.route(web::delete().to_async(endpoints::sell_item)),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.route("/claims", web::get().to_async(endpoints::player_claims))
|
|
||||||
.route(
|
|
||||||
"/items",
|
|
||||||
web::get().to_async(move |pool: AppPool| {
|
|
||||||
db_call(pool, move |api| api.fetch_inventory())
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.service(
|
|
||||||
web::scope("/admin")
|
|
||||||
.route(
|
|
||||||
"/resolve-claims",
|
|
||||||
web::get().to_async(move |pool: AppPool| {
|
|
||||||
db_call(pool, move |api| api.as_admin().resolve_claims())
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/add-loot",
|
|
||||||
web::post().to_async(
|
|
||||||
move |pool: AppPool, data: web::Json<Vec<Item>>| {
|
|
||||||
db_call(pool, move |api| {
|
|
||||||
api.as_admin().add_loot(data.to_vec())
|
|
||||||
})
|
|
||||||
},
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/add-player",
|
|
||||||
web::get().to_async(
|
|
||||||
move |pool: AppPool, data: web::Json<endpoints::NewPlayer>| {
|
|
||||||
db_call(pool, move |api| {
|
|
||||||
api.as_admin().add_player(&data.name, data.wealth)
|
|
||||||
})
|
|
||||||
},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.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")?
|
||||||
|
|||||||
Reference in New Issue
Block a user