starts improving REST Api

This commit is contained in:
2019-08-04 21:23:01 +02:00
parent e56c8df121
commit a0e4a02e0f
4 changed files with 72 additions and 51 deletions

View File

@@ -120,13 +120,10 @@ impl<'q> AsPlayer<'q> {
Ok(models::Item::owned_by(self.id).load(self.conn)?) Ok(models::Item::owned_by(self.id).load(self.conn)?)
} }
/// Buy an item and add it to this player chest /// Buy an item and add it to this player chest
///
/// TODO: Items should be picked from a custom list /// TODO: Items should be picked from a custom list
/// ///
/// # Panics /// # Returns
/// /// Result containing the difference in coins after operation
/// This currently panics if player wealth fails to be updated, as this is
/// a serious error.
pub fn buy<'a>(self, name: &'a str, price: i32) -> ActionResult<(i32, i32, i32, i32)> { pub fn buy<'a>(self, name: &'a str, price: i32) -> ActionResult<(i32, i32, i32, i32)> {
self.conn.transaction(|| { self.conn.transaction(|| {
let new_item = models::item::NewLoot::to_player(self.id, (name, price)); let new_item = models::item::NewLoot::to_player(self.id, (name, price));
@@ -139,14 +136,11 @@ impl<'q> AsPlayer<'q> {
})?; })?;
self.update_wealth(-(price as f32)) self.update_wealth(-(price as f32))
}) })
} }
/// Sell an item from this player chest /// Sell an item from this player chest
/// ///
/// # Panics /// # Returns
/// /// Result containing the difference in coins after operation
/// This currently panics if player wealth fails to be updated, as this is
/// a serious error.
pub fn sell( pub fn sell(
self, self,
loot_id: i32, loot_id: i32,

View File

@@ -18,12 +18,28 @@ export const Api = {
return fetch(API_ENDPOINT(playerId + "/loot")) return fetch(API_ENDPOINT(playerId + "/loot"))
.then(r => r.json()) .then(r => r.json())
}, },
putClaim (playerId, itemId) { putClaim (player_id, item_id) {
return fetch(API_ENDPOINT(playerId + "/claim/" + itemId)) const payload = { player_id, item_id };
return fetch(API_ENDPOINT("claims"),
{
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
})
.then(r => r.json()) .then(r => r.json())
}, },
unClaim (playerId, itemId) { unClaim (player_id, item_id) {
return fetch(API_ENDPOINT(playerId + "/unclaim/" + itemId)) const payload = { player_id, item_id };
return fetch(API_ENDPOINT("claims"),
{
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
})
.then(r => r.json()) .then(r => r.json())
}, },
updateWealth (playerId, goldValue) { updateWealth (playerId, goldValue) {
@@ -83,7 +99,7 @@ export const AppStorage = {
// Sets a new active player by id // Sets a new active player by id
setActivePlayer (newPlayerId) { setActivePlayer (newPlayerId) {
if (this.debug) console.log('setActivePlayer to ', newPlayerId) if (this.debug) console.log('setActivePlayer to ', newPlayerId)
this.state.player_id = newPlayerId this.state.player_id = Number(newPlayerId)
document.cookie = `player_id=${newPlayerId};`; document.cookie = `player_id=${newPlayerId};`;
}, },
// Show/Hide player's chest // Show/Hide player's chest

View File

@@ -2,6 +2,7 @@ extern crate actix_web;
extern crate dotenv; extern crate dotenv;
extern crate env_logger; extern crate env_logger;
extern crate lootalot_db; extern crate lootalot_db;
extern crate serde;
mod server; mod server;

View File

@@ -4,7 +4,7 @@ use actix_web::{web, App, Error, HttpResponse, HttpServer};
use futures::Future; use futures::Future;
use lootalot_db::{DbApi, Pool, QueryResult}; use lootalot_db::{DbApi, Pool, QueryResult};
use std::env; use std::env;
use serde::{Serialize, Deserialize};
type AppPool = web::Data<Pool>; type AppPool = web::Data<Pool>;
/// Wraps call to the DbApi and process its result as a async HttpResponse /// Wraps call to the DbApi and process its result as a async HttpResponse
@@ -49,6 +49,12 @@ pub fn db_call<
}) })
} }
#[derive(Serialize, Deserialize, Debug)]
struct PlayerClaim {
player_id: i32,
item_id: i32,
}
pub(crate) fn serve() -> std::io::Result<()> { pub(crate) 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");
dbg!(&www_root); dbg!(&www_root);
@@ -60,7 +66,7 @@ pub(crate) fn serve() -> std::io::Result<()> {
.wrap( .wrap(
Cors::new() Cors::new()
.allowed_origin("http://localhost:8080") .allowed_origin("http://localhost:8080")
.allowed_methods(vec!["GET", "POST"]) .allowed_methods(vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"])
.max_age(3600), .max_age(3600),
) )
.service( .service(
@@ -71,11 +77,25 @@ pub(crate) fn serve() -> std::io::Result<()> {
db_call(pool, move |api| api.fetch_players()) db_call(pool, move |api| api.fetch_players())
}), }),
) )
.route( .service(
"/claims", web::resource("/claims")
web::get().to_async(move |pool: AppPool| { .route(web::get()
db_call(pool, move |api| api.fetch_claims()) .to_async(move |pool: AppPool| {
}), db_call(pool, move |api| api
.fetch_claims())
}))
.route(web::put()
.to_async(move |pool: AppPool, data: web::Json<PlayerClaim>| {
db_call(pool, move |api| api
.as_player(data.player_id)
.claim(data.item_id))
}))
.route(web::delete()
.to_async(move |pool: AppPool, data: web::Json<PlayerClaim>| {
db_call(pool, move |api| api
.as_player(data.player_id)
.unclaim(data.item_id))
}))
) )
.route( .route(
"/{player_id}/update-wealth/{amount}", "/{player_id}/update-wealth/{amount}",
@@ -89,26 +109,15 @@ pub(crate) fn serve() -> std::io::Result<()> {
db_call(pool, move |api| api.as_player(*player_id).loot()) db_call(pool, move |api| api.as_player(*player_id).loot())
}), }),
) )
.service(web::scope("/admin")
.route( .route(
"/{player_id}/claim/{item_id}", "/resolve-claims",
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, i32)>| {
db_call(pool, move |api| api.as_player(data.0).claim(data.1))
}),
)
.route(
"/{player_id}/unclaim/{item_id}",
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, i32)>| {
db_call(pool, move |api| api.as_player(data.0).unclaim(data.1))
}),
)
.route(
"/admin/resolve-claims",
web::get().to_async(move |pool: AppPool| { web::get().to_async(move |pool: AppPool| {
db_call(pool, move |api| api.as_admin().resolve_claims()) db_call(pool, move |api| api.as_admin().resolve_claims())
}), }),
) )
.route( .route(
"/admin/add-player/{name}/{wealth}", "/add-player/{name}/{wealth}",
web::get().to_async( web::get().to_async(
move |pool: AppPool, data: web::Path<(String, f32)>| { move |pool: AppPool, data: web::Path<(String, f32)>| {
db_call(pool, move |api| { db_call(pool, move |api| {
@@ -116,7 +125,8 @@ pub(crate) fn serve() -> std::io::Result<()> {
}) })
}, },
), ),
), )
)
) )
.service(fs::Files::new("/", www_root.clone()).index_file("index.html")) .service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
}) })