From 60a6e69f67cc1372a341bfc31c6c82d45d4b5d79 Mon Sep 17 00:00:00 2001 From: Artus Date: Fri, 18 Oct 2019 14:35:06 +0200 Subject: [PATCH] refactor PlayerView, plans to replace ApiStorage.js by lootalot.js api module --- lootalot_db/src/models/player.rs | 6 +- lootalot_front/src/components/PlayerView.js | 99 +++++++++++---------- lootalot_front/src/lootalot.js | 22 +++++ src/api.rs | 17 ++-- src/server.rs | 4 +- 5 files changed, 93 insertions(+), 55 deletions(-) create mode 100644 lootalot_front/src/lootalot.js diff --git a/lootalot_db/src/models/player.rs b/lootalot_db/src/models/player.rs index b0f95c0..a3c0ad8 100644 --- a/lootalot_db/src/models/player.rs +++ b/lootalot_db/src/models/player.rs @@ -3,7 +3,7 @@ use crate::{DbConnection, QueryResult}; use diesel::prelude::*; /// Representation of a player in database -#[derive(Queryable, Serialize, Deserialize, Debug)] +#[derive(Identifiable, Queryable, Serialize, Deserialize, Debug)] pub struct Player { /// DB Identitier pub id: i32, @@ -29,6 +29,10 @@ impl<'q> Players<'q> { players::table.load(self.0) } + pub fn find(&self, id: i32) -> QueryResult { + players::table.find(id).first(self.0) + } + pub fn add(&self, name: &str, wealth: f32) -> QueryResult { diesel::insert_into(players::table) .values(&NewPlayer::create(name, wealth)) diff --git a/lootalot_front/src/components/PlayerView.js b/lootalot_front/src/components/PlayerView.js index cd76e0f..e7ae3fb 100644 --- a/lootalot_front/src/components/PlayerView.js +++ b/lootalot_front/src/components/PlayerView.js @@ -1,70 +1,73 @@ -import { Api, AppStorage } from '../AppStorage' +import { api } from '../lootalot.js' export default { props: ["id"], data () { return { + player: { + name: "Loading", + id: 0, + cp: '-', sp: '-', gp: '-', pp: '-', + debt: 0, + }, notifications: [], loot: [], }}, methods: { - updateWealth (value) { - AppStorage.updatePlayerWealth(value) - .then(_ => {if (AppStorage.debug) this.notifications.push("Wealth updated")}) - .catch(e => {if (AppStorage.debug) console.error("wealthUpdate Error", e)}) + parseUpdate (update) { + if (update.Wealth) { + var w = update.Wealth; + this.player.cp += w.cp; + this.player.sp += w.sp; + this.player.gp += w.gp; + this.player.pp += w.pp; + } + if (update.ItemAdded) { + var i = update.ItemAdded; + this.loot.push(i); + } + if (update.ItemRemoved) { + var i = update.ItemRemoved; + this.loot.splice(this.loot.indexOf(i), 1); + } + if (update.ClaimAdded || update.ClaimRemoved) { + console.error("cannot handle claim !", update); + } }, - putClaim (itemId) { - AppStorage.putRequest(itemId) - .then(_ => { if (AppStorage.debug) this.notifications.push("Claim put")}) - }, - withdrawClaim (itemId) { - AppStorage.cancelRequest(itemId) - .then(_ => { if (AppStorage.debug) this.notifications.push("Claim withdrawn")}) - - }, - buyItems(items) { - AppStorage.buyItems(items) - .then((items) => { - this.notifications.push(`Bought ${items.length} items`) - this.loot = this.loot.concat(items); + call (resource, method, payload) { + return api.fetch(`players/${this.id}/${resource}`, method, payload) + .then(response => { + if (response.notification) { + this.notifications.push(response.notification) + } + if (response.errors) { + this.notifications.push(response.errors) + } + if (response.updates) { + for (var idx in response.updates) { + this.parseUpdate(response.updates[idx]); + } + } + return response.value; }) }, - sellItems (items) { - AppStorage.sellItems(items) - .then(_ => { - this.notifications.push(`Sold ${items.length} items`) - for (var idx in items) { - var to_remove = items[idx][0]; - this.loot = this.loot.filter((item) => item.id != to_remove); - } - }) - }, - parseLoot (items) { - this.loot = []; - items.map(item => { - this.loot.push(item); - }); - } + updateWealth (value) { this.call("wealth", "PUT", Number(value)) }, + putClaim (itemId) { this.call("claims", "PUT", itemId) }, + withdrawClaim (itemId) { this.call("claims", "DELETE", itemId) }, + buyItems(items) { this.call("loot", "PUT", items) }, + sellItems (items) { this.call("loot", "DELETE", items) }, }, watch: { id: { immediate: true, handler: function(newId) { - Api.fetchLoot(newId).then(this.parseLoot); - } - }, - }, - computed: { - player () { - if (!AppStorage.state.initiated) { - return { name: "Loading", - id: 0, - cp: '-', sp: '-', gp: '-', pp: '-', - debt: 0 }; - } else { - return AppStorage.state.player_list[this.id]; + this.call("", "GET", null) + .then(p => this.player = p) + this.call("loot", "GET", null) + .then(l => this.loot = l) } }, }, + computed: {}, render () { return this.$scopedSlots.default({ player: this.player, diff --git a/lootalot_front/src/lootalot.js b/lootalot_front/src/lootalot.js new file mode 100644 index 0000000..a8049b2 --- /dev/null +++ b/lootalot_front/src/lootalot.js @@ -0,0 +1,22 @@ +import Vue from 'vue' + +const API_BASEURL = "http://localhost:8088/api/" +const API_ENDPOINT = function (tailString) { + return API_BASEURL + tailString; +} + +export const api = { + fetch: function(endpoint, method, payload) { + var config = { + method, + headers: { + 'Content-Type': 'application/json', + }, + }; + if (payload) { + config.body = JSON.stringify(payload); + } + return fetch(API_ENDPOINT(endpoint), config) + .then(r => r.json()); + } +} diff --git a/src/api.rs b/src/api.rs index 38d98d5..0956e2b 100644 --- a/src/api.rs +++ b/src/api.rs @@ -13,6 +13,7 @@ pub enum Update { /// Every value which can be queried #[derive(Debug)] pub enum Value { + Player(db::Player), Item(db::Item), Claim(db::Claim), ItemList(Vec), @@ -23,11 +24,12 @@ pub enum Value { impl serde::Serialize for Value { fn serialize(&self, serializer: S) -> Result { match self { - Self::Item(v) => v.serialize(serializer), - Self::Claim(v) => v.serialize(serializer), - Self::ItemList(v) => v.serialize(serializer), - Self::ClaimList(v) => v.serialize(serializer), - Self::PlayerList(v) => v.serialize(serializer), + Value::Player(v) => v.serialize(serializer), + Value::Item(v) => v.serialize(serializer), + Value::Claim(v) => v.serialize(serializer), + Value::ItemList(v) => v.serialize(serializer), + Value::ClaimList(v) => v.serialize(serializer), + Value::PlayerList(v) => v.serialize(serializer), } } } @@ -82,6 +84,7 @@ pub enum ApiActions { FetchInventory, FetchClaims, // Player actions + FetchPlayer(i32), FetchLoot(i32), UpdateWealth(i32, f32), BuyItems(i32, Vec<(i32, Option)>), @@ -114,6 +117,9 @@ pub fn execute( ApiActions::FetchClaims => { response.set_value(Value::ClaimList(db::fetch_claims(conn)?)); } + ApiActions::FetchPlayer(id) => { + response.set_value(Value::Player(db::Players(conn).find(id)?)); + } ApiActions::FetchLoot(id) => { response.set_value(Value::ItemList(db::LootManager(conn, id).all()?)); } @@ -121,6 +127,7 @@ pub fn execute( response.push_update(Update::Wealth( db::AsPlayer(conn, id).update_wealth(amount)?, )); + response.notify(format!("Money updated !")); } ApiActions::BuyItems(id, params) => { let mut cumulated_diff: Vec = Vec::with_capacity(params.len()); diff --git a/src/server.rs b/src/server.rs index 02e8901..870087f 100644 --- a/src/server.rs +++ b/src/server.rs @@ -41,7 +41,9 @@ fn configure_app(config: &mut web::ServiceConfig) { ) // List of players .service( web::scope("/{player_id}") - //.route(web::get().to_async(...)) // Details of player + .route("/", web::get().to_async(|pool, player: PlayerId| { + db_call(pool, Q::FetchPlayer(*player)) + })) .service( web::resource("/claims") //.route(web::get().to_async(endpoints::player_claims))