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