Compare commits
3 Commits
36c8f24fdc
...
b8968aebbd
| Author | SHA1 | Date | |
|---|---|---|---|
| b8968aebbd | |||
| c95c13bf18 | |||
| 5a792edb20 |
@@ -13,6 +13,7 @@ env_logger = "*"
|
||||
futures = "0.1"
|
||||
diesel = "*"
|
||||
serde = "*"
|
||||
actix-cors = "0.1.0"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
|
||||
Binary file not shown.
@@ -25,19 +25,20 @@ pub type ActionResult = QueryResult<bool>;
|
||||
/// ::new() -> DbApi<'q> (Db finds a connection by itself, usefull for cli)
|
||||
/// ::with_conn(conn) -> DbApi<'q> (uses a user-defined connection)
|
||||
/// v .fetch_players()
|
||||
/// x .fetch_inventory()
|
||||
/// v .fetch_inventory()
|
||||
/// v .fetch_claims()
|
||||
/// v .as_player(player_id) -> AsPlayer<'q>
|
||||
/// v .loot() -> List of items owned (Vec<Item>)
|
||||
/// x .claim(item_id) -> Success status (bool)
|
||||
/// x .unclaim(item_id) -> Success status (bool)
|
||||
/// x .sell(item_id) -> Success status (bool, earned)
|
||||
/// x .buy(inventory_item_id) -> Success status (bool, cost)
|
||||
/// x .update_wealth(gold_pieces) -> Success status (bool, new_wealth)
|
||||
/// x .as_admin()
|
||||
/// x .add_loot([inventory_item_ids]) -> Success status
|
||||
/// v .claim(loot_id) -> Success status (bool)
|
||||
/// v .unclaim(loot_id) -> Success status (bool)
|
||||
/// x .sell(loot_id) -> Success status (bool, earned)
|
||||
/// x .buy(item_desc) -> Success status (bool, cost)
|
||||
/// v .update_wealth(value_in_gold) -> Success status (bool, new_wealth)
|
||||
/// v .as_admin()
|
||||
/// x .add_loot(identifier, [items_desc]) -> Success status
|
||||
/// x .sell_loot([players], [excluded_item_ids]) -> Success status (bool, player_share)
|
||||
/// x .resolve_claims()
|
||||
/// x .add_player(player_data)
|
||||
/// v .add_player(player_data)
|
||||
///
|
||||
pub struct DbApi<'q>(&'q DbConnection);
|
||||
|
||||
@@ -70,6 +71,13 @@ impl<'q> DbApi<'q> {
|
||||
.load::<models::Item>(self.0)?
|
||||
)
|
||||
}
|
||||
|
||||
pub fn fetch_claims(self) -> QueryResult<Vec<models::Claim>> {
|
||||
Ok(
|
||||
schema::claims::table
|
||||
.load::<models::Claim>(self.0)?
|
||||
)
|
||||
}
|
||||
/// Wrapper for acting as a specific player
|
||||
///
|
||||
/// The DbApi is moved inside a new AsPlayer object.
|
||||
@@ -82,6 +90,11 @@ impl<'q> DbApi<'q> {
|
||||
pub fn as_player(self, id: i32) -> AsPlayer<'q> {
|
||||
AsPlayer { id, conn: self.0 }
|
||||
}
|
||||
|
||||
/// Wrapper for acting as the admin
|
||||
pub fn as_admin(self) -> AsAdmin<'q> {
|
||||
AsAdmin(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper for interactions of players with the database
|
||||
@@ -99,15 +112,20 @@ impl<'q> AsPlayer<'q> {
|
||||
.load(self.conn)?
|
||||
)
|
||||
}
|
||||
pub fn update_wealth(self, value: f32) -> ActionResult {
|
||||
/// Adds the value in gold to the player's wealth.
|
||||
///
|
||||
/// Value can be negative to substract wealth.
|
||||
pub fn update_wealth(self, value_in_gp: f32) -> ActionResult {
|
||||
use schema::players::dsl::*;
|
||||
let current_wealth = players.find(self.id)
|
||||
let current_wealth = players
|
||||
.find(self.id)
|
||||
.select((cp, sp, gp, pp))
|
||||
.first::<models::WealthUpdate>(self.conn)?;
|
||||
// TODO: improve this
|
||||
// should be move inside a WealthUpdate method
|
||||
let update =
|
||||
models::WealthUpdate::from_gp(current_wealth.to_gp() + value);
|
||||
let update = models::WealthUpdate::from_gp(
|
||||
current_wealth.to_gp() + value_in_gp
|
||||
);
|
||||
diesel::update(players)
|
||||
.filter(id.eq(self.id))
|
||||
.set(&update)
|
||||
@@ -117,11 +135,37 @@ impl<'q> AsPlayer<'q> {
|
||||
}
|
||||
/// Put a claim on a specific item
|
||||
pub fn claim(self, item: i32) -> ActionResult {
|
||||
Ok(false)
|
||||
let request = models::NewClaim { player_id: self.id, loot_id: item };
|
||||
diesel::insert_into(schema::claims::table)
|
||||
.values(&request)
|
||||
.execute(self.conn)
|
||||
.map(|r| match r { 1 => true, _ => false })
|
||||
}
|
||||
/// Withdraw claim
|
||||
pub fn unclaim(self, item: i32) -> ActionResult {
|
||||
use schema::claims::dsl::*;
|
||||
diesel::delete(
|
||||
claims
|
||||
.filter(loot_id.eq(item))
|
||||
.filter(player_id.eq(self.id)))
|
||||
.execute(self.conn)
|
||||
.map(|r| match r { 1 => true, _ => false })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct AsAdmin<'q>(&'q DbConnection);
|
||||
|
||||
impl<'q> AsAdmin<'q> {
|
||||
|
||||
pub fn add_player(self, name: String, start_wealth: f32) -> ActionResult {
|
||||
diesel::insert_into(schema::players::table)
|
||||
.values(&models::NewPlayer::create(&name, start_wealth))
|
||||
.execute(self.0)
|
||||
.map(|r| match r { 1 => true, _ => false })
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_pool() -> Pool {
|
||||
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
|
||||
dbg!( &connspec );
|
||||
|
||||
17
lootalot_db/src/models/claim.rs
Normal file
17
lootalot_db/src/models/claim.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use diesel::prelude::*;
|
||||
use crate::schema::claims;
|
||||
|
||||
#[derive(Queryable, Serialize, Debug)]
|
||||
pub struct Claim {
|
||||
id: i32,
|
||||
player_id: i32,
|
||||
loot_id: i32,
|
||||
resolve: i32,
|
||||
}
|
||||
|
||||
#[derive(Insertable, Debug)]
|
||||
#[table_name="claims"]
|
||||
pub struct NewClaim {
|
||||
pub player_id: i32,
|
||||
pub loot_id: i32,
|
||||
}
|
||||
@@ -3,13 +3,11 @@ use diesel::dsl::{Eq, Filter, Select};
|
||||
use crate::schema::{looted, items};
|
||||
use crate::DbConnection;
|
||||
|
||||
type ItemColumns = ( looted::id, looted::name, looted::base_price, );
|
||||
type ItemColumns =
|
||||
( looted::id, looted::name, looted::base_price, );
|
||||
const ITEM_COLUMNS: ItemColumns =
|
||||
( looted::id, looted::name, looted::base_price, );
|
||||
type OwnedBy = Select<OwnedLoot, ItemColumns>;
|
||||
const ITEM_COLUMNS: ItemColumns = ( looted::id, looted::name, looted::base_price, );
|
||||
|
||||
/// New type to handle the inventory (items table)
|
||||
/// This will be used to reduce confusion with looted items.
|
||||
struct InventoryItem(Item);
|
||||
|
||||
/// Represents a unique item in inventory
|
||||
///
|
||||
@@ -43,6 +41,15 @@ struct Loot {
|
||||
owner: i32,
|
||||
}
|
||||
|
||||
impl Loot {
|
||||
/// A filter on Loot that is owned by given player
|
||||
fn owned_by(id: i32) -> OwnedLoot {
|
||||
looted::table
|
||||
.filter(looted::owner_id.eq(id))
|
||||
}
|
||||
}
|
||||
|
||||
type ItemDesc<'a> = (&'a str, i32);
|
||||
/// An item being looted or bought.
|
||||
///
|
||||
/// The owner is set to 0 in case of looting,
|
||||
@@ -56,41 +63,19 @@ struct NewLoot<'a> {
|
||||
}
|
||||
|
||||
impl<'a> NewLoot<'a> {
|
||||
fn insert(&self, conn: &DbConnection) -> QueryResult<i32> {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl Loot {
|
||||
/// A filter on Loot that is owned by given player
|
||||
fn owned_by(id: i32) -> OwnedLoot {
|
||||
looted::table
|
||||
.filter(looted::owner_id.eq(id))
|
||||
}
|
||||
/// Loot an item, adding it to the group chest
|
||||
fn loot(name: &str, base_price: i32) -> Result<i32, ()> {
|
||||
let loot = NewLoot{ name, base_price, owner_id: 0 };
|
||||
// Insert into table
|
||||
// Retrieve id of created loot
|
||||
let loot_id = 0;
|
||||
Ok(loot_id)
|
||||
}
|
||||
/// Delete the item, returning the gained wealth
|
||||
fn sell(_modifier: i8) -> Result<i32, ()> {
|
||||
// Calculate sell value : base_value / 2 * modifier
|
||||
// Delete recording of loot
|
||||
Err(())
|
||||
}
|
||||
fn buy(buyer_id: i32, item_desc: (&str, i32)) -> Result<i32, ()> {
|
||||
let loot = NewLoot{
|
||||
name: item_desc.0,
|
||||
base_price: item_desc.1,
|
||||
owner_id: buyer_id
|
||||
};
|
||||
// Insert into table
|
||||
// Retrieve id of created loot;
|
||||
|
||||
// Withdraw value from player wealth.
|
||||
Ok(item_desc.1)
|
||||
fn to_group(desc: ItemDesc<'a>) -> Self {
|
||||
Self {
|
||||
name: desc.0,
|
||||
base_price: desc.1,
|
||||
owner_id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_player(player: i32, desc: ItemDesc<'a>) -> Self {
|
||||
Self {
|
||||
name: desc.0,
|
||||
base_price: desc.1,
|
||||
owner_id: player,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod item;
|
||||
mod player;
|
||||
mod claim;
|
||||
|
||||
pub use item::Item;
|
||||
pub use player::Player;
|
||||
pub use player::WealthUpdate;
|
||||
pub use player::{Player, NewPlayer, WealthUpdate};
|
||||
pub use claim::{NewClaim, Claim};
|
||||
|
||||
@@ -72,6 +72,19 @@ pub struct NewPlayer<'a> {
|
||||
pp: i32,
|
||||
}
|
||||
|
||||
impl<'a> NewPlayer<'a> {
|
||||
pub fn create(name: &'a str, wealth: f32) -> Self {
|
||||
let wealth = WealthUpdate::from_gp(wealth);
|
||||
Self {
|
||||
name,
|
||||
cp: wealth.cp,
|
||||
sp: wealth.sp,
|
||||
gp: wealth.gp,
|
||||
pp: wealth.pp,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -7,7 +7,9 @@ const PLAYER_LIST = [
|
||||
];
|
||||
|
||||
const fetchPlayerList = function () {
|
||||
|
||||
fetch("http://localhost:8088/players")
|
||||
.then(r => r.json())
|
||||
.then(r => console.log(r));
|
||||
};
|
||||
|
||||
const fetchRequests = function () {
|
||||
@@ -25,6 +27,7 @@ export const AppStorage = {
|
||||
// Initiate the state
|
||||
initStorage (playerId) {
|
||||
if (this.debug) console.log('Initiate with player : ', playerId)
|
||||
fetchPlayerList();
|
||||
this.state.player_id = playerId;
|
||||
for (var idx in PLAYER_LIST) {
|
||||
var player = PLAYER_LIST[idx];
|
||||
|
||||
@@ -6,6 +6,7 @@ extern crate lootalot_db;
|
||||
mod server;
|
||||
|
||||
fn main() {
|
||||
std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
env_logger::init();
|
||||
dotenv::dotenv().ok();
|
||||
// TODO: Build a cli app with complete support of DbApi
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::env;
|
||||
use futures::Future;
|
||||
use actix_files as fs;
|
||||
use actix_web::{web, App, HttpServer, HttpResponse, Error};
|
||||
use actix_cors::Cors;
|
||||
use lootalot_db::{Pool, DbApi, QueryResult};
|
||||
|
||||
type AppPool = web::Data<Pool>;
|
||||
@@ -56,24 +57,38 @@ pub(crate) fn serve() -> std::io::Result<()> {
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.data(pool.clone())
|
||||
.wrap(
|
||||
Cors::new()
|
||||
.allowed_origin("http://localhost:8080")
|
||||
.allowed_methods(vec!["GET", "POST"])
|
||||
.max_age(3600)
|
||||
)
|
||||
.route(
|
||||
"/players",
|
||||
web::get().to_async(move |pool: AppPool| {
|
||||
db_call(pool, move |api| api.fetch_players())
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/claims",
|
||||
web::get().to_async(move |pool: AppPool| db_call(pool, move |api| api.fetch_claims())),
|
||||
)
|
||||
.route(
|
||||
"/update-wealth/{player_id}/{amount}",
|
||||
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, f32)>| {
|
||||
let (player, gold) = *data;
|
||||
db_call(pool, move |api| api.as_player(player).update_wealth(gold))
|
||||
db_call(pool, move |api| api.as_player(data.0).update_wealth(data.1))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/loot/{player_id}",
|
||||
web::get().to_async(move |pool: AppPool, player_id: web::Path<i32>| {
|
||||
let player_id: i32 = *player_id;
|
||||
db_call(pool, move |api| api.as_player(player_id).loot())
|
||||
db_call(pool, move |api| api.as_player(*player_id).loot())
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/admin/add-player/{name}/{wealth}",
|
||||
web::get().to_async(move |pool: AppPool, data: web::Path<(String, f32)>| {
|
||||
db_call(pool, move |api| api.as_admin().add_player(data.0.clone(), data.1))
|
||||
}),
|
||||
)
|
||||
.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
||||
|
||||
Reference in New Issue
Block a user