moves api to its own module, thinking about design to choose
This commit is contained in:
83
src/api.rs
Normal file
83
src/api.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use actix_web::{web, web::Json, Error, HttpResponse, Result};
|
||||
use futures::Future;
|
||||
|
||||
use lootalot_db::{Pool};
|
||||
|
||||
// Wrapper for database queries.
|
||||
//fn db_query(q: fn(...)) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||
//
|
||||
//}
|
||||
|
||||
mod player {
|
||||
use lootalot_db::{Player as PlayerData, Item, ActionResult, QueryResult, DbConnection};
|
||||
|
||||
/// A reference to a player in database
|
||||
pub(super) struct Player(pub(super) i32);
|
||||
|
||||
impl Player {
|
||||
/// Fetch all players from db
|
||||
pub(super) fn all(conn: &DbConnection) -> QueryResult<Vec<PlayerData>> {
|
||||
PlayerData::fetch_list(conn)
|
||||
}
|
||||
/// Fetch the content of a player's chest
|
||||
pub(super) fn loot(self, conn: &DbConnection) -> QueryResult<Vec<Item>> {
|
||||
PlayerData::fetch_loot(self.0, conn)
|
||||
}
|
||||
pub(super) fn claim(self, item: i32, conn: &DbConnection) -> ActionResult {
|
||||
PlayerData::action_claim_object(self.0, item, conn)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
pub fn players_list(
|
||||
pool: web::Data<Pool>
|
||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||
web::block(move || {
|
||||
let conn = pool.get().unwrap();
|
||||
player::Player::all(&conn)
|
||||
})
|
||||
.then(|res| match res {
|
||||
Ok(players) => {
|
||||
HttpResponse::Ok().json(players)
|
||||
}
|
||||
Err(_) => {
|
||||
HttpResponse::InternalServerError().finish()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn chest_content(
|
||||
player_id: web::Path<i32>,
|
||||
pool: web::Data<Pool>
|
||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||
web::block(move || {
|
||||
let conn = pool.get().unwrap();
|
||||
player::Player(*player_id).loot(&conn)
|
||||
})
|
||||
.then(|res| match res {
|
||||
Ok(items) => HttpResponse::Ok().json(items),
|
||||
Err(_) => HttpResponse::InternalServerError().finish(),
|
||||
})
|
||||
}
|
||||
|
||||
fn put_request(
|
||||
params: web::Path<(i32, i32)>,
|
||||
pool: web::Data<Pool>
|
||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||
web::block(move || {
|
||||
let (player_id, item_id) = *params;
|
||||
let conn = pool.get().unwrap();
|
||||
player::Player(player_id).claim(item_id, &conn)
|
||||
})
|
||||
.then(|res| match res {
|
||||
Ok(status) => HttpResponse::Ok().json(status),
|
||||
Err(_) => HttpResponse::InternalServerError().finish(),
|
||||
})
|
||||
}
|
||||
|
||||
fn withdraw_request(_player_id: i32, _item_id: i32) -> Result<Json<bool>> {
|
||||
Ok(Json(false))
|
||||
}
|
||||
Reference in New Issue
Block a user