Refactored into service directory

This commit is contained in:
Benjamin Sherriff
2023-10-04 16:52:09 -04:00
parent be4ab2bc69
commit 06f8af6051
63 changed files with 11 additions and 577 deletions

View File

View File

View File

@@ -0,0 +1,3 @@
mod model;
pub use model::*;

View File

@@ -0,0 +1,46 @@
use std::str::FromStr;
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize)]
pub enum AbilityType {
#[serde(rename = "strength")]
Strength,
#[serde(rename = "dexterity")]
Dexterity,
#[serde(rename = "constitution")]
Constitution,
#[serde(rename = "intelligence")]
Intelligence,
#[serde(rename = "wisdom")]
Wisdom,
#[serde(rename = "charisma")]
Charisma
}
impl AbilityType {
pub fn to_string(&self) -> String {
match self {
AbilityType::Strength => "Strength".to_string(),
AbilityType::Dexterity => "Dexterity".to_string(),
AbilityType::Constitution => "Constitution".to_string(),
AbilityType::Intelligence => "Intelligence".to_string(),
AbilityType::Wisdom => "Wisdom".to_string(),
AbilityType::Charisma => "Charisma".to_string()
}
}
}
impl FromStr for AbilityType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Strength" => Ok(AbilityType::Strength),
"Dexterity" => Ok(AbilityType::Dexterity),
"Constitution" => Ok(AbilityType::Constitution),
"Intelligence" => Ok(AbilityType::Intelligence),
"Wisdom" => Ok(AbilityType::Wisdom),
"Charisma" => Ok(AbilityType::Charisma),
_ => Err(())
}
}
}

View File

@@ -0,0 +1,83 @@
use std::str::FromStr;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub enum ConditionType {
#[serde(rename = "blinded")]
Blinded,
#[serde(rename = "charmed")]
Charmed,
#[serde(rename = "deafened")]
Deafened,
#[serde(rename = "exhaustion")]
Exhaustion,
#[serde(rename = "frightened")]
Frightened,
#[serde(rename = "grappled")]
Grappled,
#[serde(rename = "incapacitated")]
Incapacitated,
#[serde(rename = "invisible")]
Invisible,
#[serde(rename = "paralyzed")]
Paralyzed,
#[serde(rename = "petrified")]
Petrified,
#[serde(rename = "poisoned")]
Poisoned,
#[serde(rename = "prone")]
Prone,
#[serde(rename = "restrained")]
Restrained,
#[serde(rename = "stunned")]
Stunned,
#[serde(rename = "unconscious")]
Unconscious
}
impl ConditionType {
pub fn to_string(&self) -> String {
match self {
ConditionType::Blinded => "Blinded".to_string(),
ConditionType::Charmed => "Charmed".to_string(),
ConditionType::Deafened => "Deafened".to_string(),
ConditionType::Exhaustion => "Exhaustion".to_string(),
ConditionType::Frightened => "Frightened".to_string(),
ConditionType::Grappled => "Grappled".to_string(),
ConditionType::Incapacitated => "Incapacitated".to_string(),
ConditionType::Invisible => "Invisible".to_string(),
ConditionType::Paralyzed => "Paralyzed".to_string(),
ConditionType::Petrified => "Petrified".to_string(),
ConditionType::Poisoned => "Poisoned".to_string(),
ConditionType::Prone => "Prone".to_string(),
ConditionType::Restrained => "Restrained".to_string(),
ConditionType::Stunned => "Stunned".to_string(),
ConditionType::Unconscious => "Unconscious".to_string()
}
}
}
impl FromStr for ConditionType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Blinded" => Ok(ConditionType::Blinded),
"Charmed" => Ok(ConditionType::Charmed),
"Deafened" => Ok(ConditionType::Deafened),
"Exhaustion" => Ok(ConditionType::Exhaustion),
"Frightened" => Ok(ConditionType::Frightened),
"Grappled" => Ok(ConditionType::Grappled),
"Incapacitated" => Ok(ConditionType::Incapacitated),
"Invisible" => Ok(ConditionType::Invisible),
"Paralyzed" => Ok(ConditionType::Paralyzed),
"Petrified" => Ok(ConditionType::Petrified),
"Poisoned" => Ok(ConditionType::Poisoned),
"Prone" => Ok(ConditionType::Prone),
"Restrained" => Ok(ConditionType::Restrained),
"Stunned" => Ok(ConditionType::Stunned),
"Unconscious" => Ok(ConditionType::Unconscious),
_ => Err(())
}
}
}

View File

View File

View File

@@ -0,0 +1,3 @@
mod model;
pub use model::*;

View File

@@ -0,0 +1,33 @@
use diesel::prelude::*;
use crate::db::schema::messages;
#[derive(Queryable, Selectable)]
#[diesel(table_name = messages)]
pub struct MessageDB {
pub id: String,
pub guild_id: i64,
pub channel_id: i64,
pub user_id: i64,
pub created: i64,
pub model: String,
pub request: String,
pub response: String,
pub request_tags: Vec<String>,
pub response_tags: Vec<String>,
}
#[derive(Insertable)]
#[diesel(table_name = messages)]
pub struct NewMessageDB<'a> {
pub id: &'a str,
pub guild_id: i64,
pub channel_id: i64,
pub user_id: i64,
pub created: i64,
pub model: &'a str,
pub request: &'a str,
pub response: &'a str,
pub request_tags: Vec<&'a str>,
pub response_tags: Vec<&'a str>,
}

72
service/src/db/mod.rs Normal file
View File

@@ -0,0 +1,72 @@
use crate::error_handler::ServiceError;
use diesel::{r2d2::ConnectionManager, PgConnection};
use serde::{Deserialize, Serialize};
use crate::diesel_migrations::MigrationHarness;
use lazy_static::lazy_static;
use log::{error, info};
use r2d2;
use std::env;
pub mod backgrounds;
pub mod bestiary;
pub mod classes;
pub mod conditions;
pub mod feats;
pub mod items;
pub mod messages;
pub mod options;
pub mod races;
pub mod spells;
pub mod users;
pub mod schema;
type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
pub type DbConnection = r2d2::PooledConnection<ConnectionManager<PgConnection>>;
pub const MIGRATIONS: diesel_migrations::EmbeddedMigrations = embed_migrations!();
lazy_static! {
static ref POOL: Pool = {
let username = env::var("DATABASE_USER").expect("DATABASE_USERNAME is not set");
let password = env::var("DATABASE_PASSWORD").expect("DATABASE_PASSWORD is not set");
let host = env::var("DATABASE_HOST").unwrap_or("localhost".to_string());
let name = env::var("DATABASE_NAME").expect("DATABASE_NAME is not set");
let port = env::var("DATABASE_PORT").unwrap_or("5432".to_string());
let url = format!("postgres://{}:{}@{}:{}/{}", username, password, host, port, name);
let manager = ConnectionManager::<PgConnection>::new(url);
Pool::builder().test_on_check_out(true).build(manager).expect("Failed to create db pool")
};
}
pub fn init() {
lazy_static::initialize(&POOL);
let mut pool: DbConnection = connection().expect("Failed to get db connection");
match pool.run_pending_migrations(MIGRATIONS) {
Ok(_) => info!("Database initialized"),
Err(err) => error!("Failed to initialize database; {}", err)
};
}
pub fn connection() -> Result<DbConnection, ServiceError> {
POOL.get()
.map_err(|e| ServiceError::new(500, format!("Failed getting db connection: {}", e)))
}
pub fn load_data() {
spells::load_data();
}
#[derive(Serialize, Deserialize)]
pub struct GetResponse<T> {
pub data: T,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Metadata>
}
#[derive(Serialize, Deserialize)]
pub struct Metadata {
pub total: i32,
pub limit: i32,
pub page: i32,
pub pages: i32
}

View File

View File

32
service/src/db/schema.rs Normal file
View File

@@ -0,0 +1,32 @@
diesel::table! {
messages (id) {
id -> Text,
guild_id -> BigInt,
channel_id -> BigInt,
user_id -> BigInt,
created -> BigInt,
model -> Text,
request -> Text,
response -> Text,
request_tags -> Array<Text>,
response_tags -> Array<Text>,
}
}
diesel::table! {
spells (id) {
id -> Integer,
name -> Text,
school -> Text,
level -> Integer,
ritual -> Bool,
concentration -> Bool,
classes -> Array<Text>,
damage_inflict -> Array<Text>,
damage_resist -> Array<Text>,
conditions -> Array<Text>,
saving_throw -> Array<Text>,
attack_type -> Nullable<Text>,
data -> Jsonb
}
}

View File

@@ -0,0 +1,47 @@
mod model;
mod routes;
mod types;
pub use model::*;
pub use types::*;
pub use routes::init_routes;
pub fn load_data() {
let root_path = std::env::current_dir().unwrap();
let files = [
"cantrips.json", "level_1.json", "level_2.json", "level_3.json", "level_4.json", "level_5.json", "level_6.json", "level_7.json", "level_8.json", "level_9.json"
];
let mut spells: Vec<Spell> = vec![];
for file in files {
let mut data_path = std::path::PathBuf::from(&root_path);
data_path.push(format!("data/spells/{}", file));
let path = data_path.to_str().unwrap();
match std::fs::read_to_string(path) {
Ok(data) => {
log::debug!("Loading spells from {}", path);
match serde_json::from_str::<serde_json::Value>(&data) {
Ok(json) => {
match serde_json::from_value::<Vec<Spell>>(json) {
Ok(mut new_spells) => spells.append(&mut new_spells),
Err(err) => log::error!("Failed to parse spells data: {}", err)
}
},
Err(err) => log::error!("Failed to parse spells data to value: {}", err)
};
},
Err(err) => log::error!("Failed to read from {}: {}", file, err)
};
}
let count = QuerySpell::get_count(&QueryFilters::default()).unwrap();
if count >= spells.len() as i64 {
log::warn!("Spell data is already loaded");
return;
}
for spell in spells {
let spell_name = spell.name.clone();
match InsertSpell::insert(spell.into()) {
Ok(_) => {},
Err(err) => log::error!("Failed to insert '{}' spell: {}", spell_name, err)
}
}
}

View File

@@ -0,0 +1,290 @@
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{db::{schema::spells::{self}, classes::AbilityType, conditions::ConditionType}, error_handler::ServiceError};
use super::{SchoolType, CastingTime, CastingType, SpellAttackType, SpellDamageType, Range, Area, Components, Duration, Source, Description, DurationType};
#[derive(Queryable, QueryableByName)]
#[diesel(table_name = spells)]
pub struct QuerySpell {
pub id: i32,
pub name: String,
pub school: String,
pub level: i32,
pub ritual: bool,
pub concentration: bool,
pub classes: Vec<String>,
pub damage_inflict: Vec<String>,
pub damage_resist: Vec<String>,
pub conditions: Vec<String>,
pub saving_throw: Vec<String>,
pub attack_type: Option<String>,
pub data: serde_json::Value,
}
#[derive(Debug)]
pub struct QueryFilters {
pub by_name: Option<String>,
pub by_schools: Option<Vec<String>>,
pub by_levels: Option<Vec<i32>>,
pub by_ritual: Option<bool>,
pub by_concentration: Option<bool>,
pub by_classes: Option<Vec<String>>,
pub by_damage_inflict: Option<Vec<String>>,
pub by_damage_resist: Option<Vec<String>>,
pub by_conditions: Option<Vec<String>>,
pub by_saving_throw: Option<Vec<String>>,
pub by_attack_type: Option<String>,
}
impl Default for QueryFilters {
fn default() -> Self {
Self {
by_name: None,
by_schools: None,
by_levels: None,
by_ritual: None,
by_concentration: None,
by_classes: None,
by_damage_inflict: None,
by_damage_resist: None,
by_conditions: None,
by_saving_throw: None,
by_attack_type: None,
}
}
}
impl QuerySpell {
pub fn get_all(filters: &QueryFilters, limit: i32, page: i32) -> Result<Vec<Self>, ServiceError> {
let mut conn = crate::db::connection()?;
let mut query = spells::table.limit(limit as i64).into_boxed();
// Limit query to page and limit
let offset = (page - 1) * limit;
query = query.offset(offset as i64);
if let Some(name) = &filters.by_name {
query = query.filter(spells::name.ilike(format!("%{}%", name)));
}
if let Some(schools) = &filters.by_schools {
query = query.filter(spells::school.eq_any(schools.iter().map(|school| school.to_string()).collect::<Vec<String>>()));
}
if let Some(levels) = &filters.by_levels {
query = query.filter(spells::level.eq_any(levels));
}
if let Some(ritual) = filters.by_ritual {
query = query.filter(spells::ritual.eq(ritual));
}
if let Some(concentration) = filters.by_concentration {
query = query.filter(spells::concentration.eq(concentration));
}
if let Some(classes) = &filters.by_classes {
query = query.filter(spells::classes.overlaps_with(classes));
}
if let Some(damage_inflict) = &filters.by_damage_inflict {
query = query.filter(spells::damage_inflict.overlaps_with(damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect::<Vec<String>>()));
}
if let Some(damage_resist) = &filters.by_damage_resist {
query = query.filter(spells::damage_resist.overlaps_with(damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect::<Vec<String>>()));
}
if let Some(conditions) = &filters.by_conditions {
query = query.filter(spells::conditions.overlaps_with(conditions.iter().map(|condition| condition.to_string()).collect::<Vec<String>>()));
}
if let Some(saving_throw) = &filters.by_saving_throw {
query = query.filter(spells::saving_throw.overlaps_with(saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect::<Vec<String>>()));
}
if let Some(attack_type) = &filters.by_attack_type {
query = query.filter(spells::attack_type.eq(attack_type.to_string()));
}
let spells = query.load::<QuerySpell>(&mut conn)?;
Ok(spells)
}
pub fn get_count(filters: &QueryFilters) -> Result<i64, ServiceError> {
let mut conn = crate::db::connection()?;
let mut query = spells::table.count().into_boxed();
if let Some(name) = &filters.by_name {
query = query.filter(spells::name.ilike(format!("%{}%", name)));
}
if let Some(schools) = &filters.by_schools {
query = query.filter(spells::school.eq_any(schools.iter().map(|school| school.to_string()).collect::<Vec<String>>()));
}
if let Some(levels) = &filters.by_levels {
query = query.filter(spells::level.eq_any(levels));
}
if let Some(ritual) = filters.by_ritual {
query = query.filter(spells::ritual.eq(ritual));
}
if let Some(concentration) = filters.by_concentration {
query = query.filter(spells::concentration.eq(concentration));
}
if let Some(classes) = &filters.by_classes {
query = query.filter(spells::classes.overlaps_with(classes));
}
if let Some(damage_inflict) = &filters.by_damage_inflict {
query = query.filter(spells::damage_inflict.overlaps_with(damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect::<Vec<String>>()));
}
if let Some(damage_resist) = &filters.by_damage_resist {
query = query.filter(spells::damage_resist.overlaps_with(damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect::<Vec<String>>()));
}
if let Some(conditions) = &filters.by_conditions {
query = query.filter(spells::conditions.overlaps_with(conditions.iter().map(|condition| condition.to_string()).collect::<Vec<String>>()));
}
if let Some(saving_throw) = &filters.by_saving_throw {
query = query.filter(spells::saving_throw.overlaps_with(saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect::<Vec<String>>()));
}
if let Some(attack_type) = &filters.by_attack_type {
query = query.filter(spells::attack_type.eq(attack_type.to_string()));
}
let count = query.get_result(&mut conn)?;
Ok(count)
}
pub fn get_by_id(id: i32) -> Result<Self, ServiceError> {
let mut conn = crate::db::connection()?;
let spell = spells::table
.filter(spells::id.eq(id))
.first::<QuerySpell>(&mut conn)?;
Ok(spell)
}
pub fn delete(id: i32) -> Result<Self, ServiceError> {
let mut conn = crate::db::connection()?;
let spell = diesel::delete(spells::table.filter(spells::id.eq(id))).get_result(&mut conn)?;
Ok(spell)
}
}
#[derive(Insertable, AsChangeset)]
#[diesel(table_name = spells)]
pub struct InsertSpell {
pub name: String,
pub school: String,
pub level: i32,
pub ritual: bool,
pub concentration: bool,
pub classes: Vec<String>,
pub damage_inflict: Vec<String>,
pub damage_resist: Vec<String>,
pub conditions: Vec<String>,
pub saving_throw: Vec<String>,
pub attack_type: Option<String>,
pub data: serde_json::Value
}
impl InsertSpell {
pub fn insert(spell: Self) -> Result<QuerySpell, ServiceError> {
let mut conn = crate::db::connection()?;
let spell = diesel::insert_into(spells::table).values(spell).get_result(&mut conn)?;
Ok(spell)
}
pub fn update(id: i32, spell: Self) -> Result<QuerySpell, ServiceError> {
let mut conn = crate::db::connection()?;
let spell = diesel::update(spells::table.filter(spells::id.eq(id))).set(spell).get_result(&mut conn)?;
Ok(spell)
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Spell {
pub name: String,
pub school: SchoolType,
pub level: i32,
pub ritual: bool,
pub casting_time: CastingTime,
#[serde(skip_serializing_if = "Option::is_none")]
pub saving_throw: Option<Vec<AbilityType>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub attack_type: Option<SpellAttackType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub damage_inflict: Option<Vec<SpellDamageType>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub damage_resist: Option<Vec<SpellDamageType>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub conditions: Option<Vec<ConditionType>>,
pub range: Range,
#[serde(skip_serializing_if = "Option::is_none")]
pub area: Option<Area>,
pub components: Components,
pub durations: Vec<Duration>,
pub classes: Vec<String>,
pub sources: Vec<Source>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<Description>
}
impl From<QuerySpell> for Spell {
fn from(query: QuerySpell) -> Self {
return match serde_json::from_value(query.data) {
Ok(data) => data,
Err(err) => {
log::error!("Failed to parse spell: {}", err);
Self {
name: "".to_string(),
school: SchoolType::Abjuration,
level: 0,
ritual: false,
casting_time: CastingTime { amount: 0, casting_type: CastingType::Action },
saving_throw: None,
attack_type: None,
damage_inflict: None,
damage_resist: None,
conditions: None,
range: Range { range_type: "".to_string(), amount: None, unit: None },
area: None,
components: Components { verbal: false, somatic: false, material: false, materials_needed: None, materials_cost: None, materials_consumed: None },
durations: vec![],
classes: vec![],
sources: vec![],
tags: None,
description: None,
}
}
}
}
}
impl Into<InsertSpell> for Spell {
fn into(self) -> InsertSpell {
return InsertSpell {
name: self.name.to_string(),
school: self.school.to_string(),
level: self.level,
ritual: self.ritual,
concentration: self.durations.iter().any(|duration| match duration.duration_type {
DurationType::Concentration => true,
_ => false
}),
classes: self.classes.iter().map(|class| class.to_string()).collect::<Vec<String>>(),
damage_inflict: match &self.damage_inflict {
Some(damage_inflict) => damage_inflict.iter().map(|damage_inflict| damage_inflict.to_string()).collect(),
None => vec![]
},
damage_resist: match &self.damage_resist {
Some(damage_resist) => damage_resist.iter().map(|damage_resist| damage_resist.to_string()).collect(),
None => vec![]
},
conditions: match &self.conditions {
Some(conditions) => conditions.iter().map(|condition| condition.to_string()).collect(),
None => vec![]
},
saving_throw: match &self.saving_throw {
Some(saving_throw) => saving_throw.iter().map(|saving_throw| saving_throw.to_string()).collect(),
None => vec![]
},
attack_type: self.attack_type.as_ref().map(|attack_type| attack_type.to_string()),
data: match serde_json::to_value(&self) {
Ok(data) => data,
Err(err) => {
log::error!("Failed to serialize spell: {}", err);
serde_json::Value::Null
}
}
}
}
}

View File

@@ -0,0 +1,177 @@
use actix_web::{get, post, put, delete, web, HttpResponse, HttpRequest, ResponseError};
use log::error;
use serde::{Serialize, Deserialize};
use crate::{db::{spells::{QuerySpell, QueryFilters}, GetResponse, Metadata}, error_handler::ServiceError};
use super::{Spell, InsertSpell};
#[derive(Serialize, Deserialize)]
struct GetAllParams {
name: Option<String>,
schools: Option<String>,
levels: Option<String>,
ritual: Option<bool>,
concentration: Option<bool>,
classes: Option<String>,
damage_inflict: Option<String>,
damage_resist: Option<String>,
conditions: Option<String>,
saving_throw: Option<String>,
attack_type: Option<String>,
limit: Option<i32>,
page: Option<i32>,
}
#[get("/spells")]
async fn get_all(req: HttpRequest) -> HttpResponse {
let params = match web::Query::<GetAllParams>::from_query(req.query_string()) {
Ok(params) => params,
Err(err) => return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
};
let mut filters = QueryFilters::default();
filters.by_name = params.name.clone();
filters.by_schools = match &params.schools {
Some(schools) => Some(schools.split(",").map(|s| s.to_string()).collect()),
None => None
};
filters.by_levels = match &params.levels {
Some(levels) => Some(levels.split(",").map(|s| match s.to_string().parse::<i32>() {
Ok(level) => level,
Err(_) => 0
}).collect()),
None => None
};
filters.by_ritual = params.ritual;
filters.by_concentration = params.concentration;
filters.by_classes = match &params.classes {
Some(classes) => Some(classes.split(",").map(|s| s.to_string()).collect()),
None => None
};
filters.by_damage_inflict = match &params.damage_inflict {
Some(damage_inflict) => Some(damage_inflict.split(",").map(|s| s.to_string()).collect()),
None => None
};
filters.by_damage_resist = match &params.damage_resist {
Some(damage_resist) => Some(damage_resist.split(",").map(|s| s.to_string()).collect()),
None => None
};
filters.by_conditions = match &params.conditions {
Some(conditions) => Some(conditions.split(",").map(|s| s.to_string()).collect()),
None => None
};
filters.by_saving_throw = match &params.saving_throw {
Some(saving_throw) => Some(saving_throw.split(",").map(|s| s.to_string()).collect()),
None => None
};
filters.by_attack_type = match &params.attack_type {
Some(attack_type) => Some(attack_type.split(",").map(|s| s.to_string()).collect()),
None => None
};
// Limit must be between 1 and 100
let limit = std::cmp::min(std::cmp::max(params.limit.unwrap_or(20), 1), 100);
let total_count = QuerySpell::get_count(&filters).unwrap();
let max_page = std::cmp::max(1, (total_count as f64 / limit as f64).ceil() as i32);
// Page must be between 1 and max_page
let page = std::cmp::min(std::cmp::max(params.page.unwrap_or(1), 1), max_page);
match web::block(move || QuerySpell::get_all(&filters, limit, page)).await.unwrap() {
Ok(spells) => {
let mut response: Vec<Spell> = Vec::new();
for spell in spells {
response.push(Spell::from(spell));
}
HttpResponse::Ok().json(GetResponse {
data: response,
metadata: Some(Metadata {
total: total_count as i32,
limit,
page,
pages: max_page
})
})
},
Err(err) => {
error!("{:?}", err.message);
ResponseError::error_response(&err)
}
}
}
#[get("/spells/{id}")]
async fn get_by_id(id: web::Path<String>) -> HttpResponse {
let id = match id.parse::<i32>() {
Ok(id) => id,
Err(err) => return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
};
match web::block(move || QuerySpell::get_by_id(id)).await.unwrap() {
Ok(spell) => HttpResponse::Ok().json(GetResponse {
data: Spell::from(spell),
metadata: None
}),
Err(err) => {
error!("{:?}", err.message);
ResponseError::error_response(&err)
}
}
}
#[post("/spells")]
async fn create(spell: web::Json<Spell>) -> HttpResponse {
match InsertSpell::insert(spell.into_inner().into()) {
Ok(spell) => HttpResponse::Created().json(Spell::from(spell)),
Err(err) => {
error!("{:?}", err.message);
ResponseError::error_response(&err)
}
}
}
#[put("/spells/{id}")]
async fn update(id: web::Path<String>, spell: web::Json<Spell>) -> HttpResponse {
let id = match id.parse::<i32>() {
Ok(id) => id,
Err(err) => return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
};
match web::block(move || InsertSpell::update(id, spell.into_inner().into())).await.unwrap() {
Ok(spell) => HttpResponse::Ok().json(Spell::from(spell)),
Err(err) => {
error!("{:?}", err.message);
ResponseError::error_response(&err)
}
}
}
#[delete("/spells/{id}")]
async fn delete(id: web::Path<String>) -> HttpResponse {
let id = match id.parse::<i32>() {
Ok(id) => id,
Err(err) => return ResponseError::error_response(&ServiceError {
status: 422,
message: err.to_string()
})
};
match web::block(move || QuerySpell::delete(id)).await.unwrap() {
Ok(spell) => HttpResponse::Ok().json(Spell::from(spell)),
Err(err) => {
error!("{:?}", err.message);
ResponseError::error_response(&err)
}
}
}
pub fn init_routes(config: &mut web::ServiceConfig) {
config.service(get_all);
config.service(get_by_id);
config.service(create);
config.service(delete);
}

View File

@@ -0,0 +1,377 @@
use std::str::FromStr;
use serde::{Deserialize, Serialize, ser::SerializeMap};
#[derive(Debug, Serialize, Deserialize)]
pub enum SchoolType {
#[serde(rename = "abjuration")]
Abjuration,
#[serde(rename = "conjuration")]
Conjuration,
#[serde(rename = "divination")]
Divination,
#[serde(rename = "enchantment")]
Enchantment,
#[serde(rename = "evocation")]
Evocation,
#[serde(rename = "illusion")]
Illusion,
#[serde(rename = "necromancy")]
Necromancy,
#[serde(rename = "transmutation")]
Transmutation
}
impl SchoolType {
pub fn to_string(&self) -> String {
match self {
SchoolType::Abjuration => "abjuration".to_string(),
SchoolType::Conjuration => "conjuration".to_string(),
SchoolType::Divination => "divination".to_string(),
SchoolType::Enchantment => "enchantment".to_string(),
SchoolType::Evocation => "evocation".to_string(),
SchoolType::Illusion => "illusion".to_string(),
SchoolType::Necromancy => "necromancy".to_string(),
SchoolType::Transmutation => "transmutation".to_string()
}
}
}
impl FromStr for SchoolType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"abjuration" => Ok(SchoolType::Abjuration),
"conjuration" => Ok(SchoolType::Conjuration),
"divination" => Ok(SchoolType::Divination),
"enchantment" => Ok(SchoolType::Enchantment),
"evocation" => Ok(SchoolType::Evocation),
"illusion" => Ok(SchoolType::Illusion),
"necromancy" => Ok(SchoolType::Necromancy),
"transmutation" => Ok(SchoolType::Transmutation),
_ => Err(())
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CastingTime {
pub amount: i32,
#[serde(rename = "unit")]
pub casting_type: CastingType
}
#[derive(Debug, Serialize, Deserialize)]
pub enum CastingType {
#[serde(rename = "action")]
Action,
#[serde(rename = "bonus")]
BonusAction,
#[serde(rename = "reaction")]
Reaction,
#[serde(rename = "minutes")]
Minutes,
#[serde(rename = "hours")]
Hours
}
// impl CastingType {
// pub fn to_string(&self) -> String {
// match self {
// CastingType::Action => "action".to_string(),
// CastingType::BonusAction => "bonus".to_string(),
// CastingType::Reaction => "reaction".to_string(),
// CastingType::Minutes => "minutes".to_string(),
// CastingType::Hours => "hours".to_string()
// }
// }
// }
// impl FromStr for CastingType {
// type Err = ();
// fn from_str(s: &str) -> Result<Self, Self::Err> {
// match s {
// "action" => Ok(CastingType::Action),
// "bonus" => Ok(CastingType::BonusAction),
// "reaction" => Ok(CastingType::Reaction),
// "minutes" => Ok(CastingType::Minutes),
// "hours" => Ok(CastingType::Hours),
// _ => Err(())
// }
// }
// }
#[derive(Debug, Serialize, Deserialize)]
pub enum SpellAttackType {
#[serde(rename = "melee")]
Melee,
#[serde(rename = "ranged")]
Ranged,
}
impl SpellAttackType {
pub fn to_string(&self) -> String {
match self {
SpellAttackType::Melee => "melee".to_string(),
SpellAttackType::Ranged => "ranged".to_string()
}
}
}
impl FromStr for SpellAttackType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"melee" => Ok(SpellAttackType::Melee),
"ranged" => Ok(SpellAttackType::Ranged),
_ => Err(())
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum SpellDamageType {
#[serde(rename = "acid")]
Acid,
#[serde(rename = "bludgeoning")]
Bludgeoning,
#[serde(rename = "cold")]
Cold,
#[serde(rename = "fire")]
Fire,
#[serde(rename = "force")]
Force,
#[serde(rename = "lightning")]
Lightning,
#[serde(rename = "necrotic")]
Necrotic,
#[serde(rename = "piercing")]
Piercing,
#[serde(rename = "poison")]
Poison,
#[serde(rename = "psychic")]
Psychic,
#[serde(rename = "radiant")]
Radiant,
#[serde(rename = "slashing")]
Slashing,
#[serde(rename = "thunder")]
Thunder
}
impl SpellDamageType {
pub fn to_string(&self) -> String {
match self {
SpellDamageType::Acid => "acid".to_string(),
SpellDamageType::Bludgeoning => "bludgeoning".to_string(),
SpellDamageType::Cold => "cold".to_string(),
SpellDamageType::Fire => "fire".to_string(),
SpellDamageType::Force => "force".to_string(),
SpellDamageType::Lightning => "lightning".to_string(),
SpellDamageType::Necrotic => "necrotic".to_string(),
SpellDamageType::Piercing => "piercing".to_string(),
SpellDamageType::Poison => "poison".to_string(),
SpellDamageType::Psychic => "psychic".to_string(),
SpellDamageType::Radiant => "radiant".to_string(),
SpellDamageType::Slashing => "slashing".to_string(),
SpellDamageType::Thunder => "thunder".to_string()
}
}
}
impl FromStr for SpellDamageType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"acid" => Ok(SpellDamageType::Acid),
"bludgeoning" => Ok(SpellDamageType::Bludgeoning),
"cold" => Ok(SpellDamageType::Cold),
"fire" => Ok(SpellDamageType::Fire),
"force" => Ok(SpellDamageType::Force),
"lightning" => Ok(SpellDamageType::Lightning),
"necrotic" => Ok(SpellDamageType::Necrotic),
"piercing" => Ok(SpellDamageType::Piercing),
"poison" => Ok(SpellDamageType::Poison),
"psychic" => Ok(SpellDamageType::Psychic),
"radiant" => Ok(SpellDamageType::Radiant),
"slashing" => Ok(SpellDamageType::Slashing),
"thunder" => Ok(SpellDamageType::Thunder),
_ => Err(())
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Range {
#[serde(rename = "type")]
pub range_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Area {
#[serde(rename = "type")]
pub area_type: AreaType,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>
}
#[derive(Debug, Serialize, Deserialize)]
pub enum AreaType {
#[serde(rename = "cone")]
Cone,
#[serde(rename = "cube")]
Cube,
#[serde(rename = "cylinder")]
Cylinder,
#[serde(rename = "line")]
Line,
#[serde(rename = "sphere")]
Sphere
}
// impl AreaType {
// pub fn to_string(&self) -> String {
// match self {
// AreaType::Cone => "cone".to_string(),
// AreaType::Cube => "cube".to_string(),
// AreaType::Cylinder => "cylinder".to_string(),
// AreaType::Line => "line".to_string(),
// AreaType::Sphere => "sphere".to_string()
// }
// }
// }
// impl FromStr for AreaType {
// type Err = ();
// fn from_str(s: &str) -> Result<Self, Self::Err> {
// match s {
// "cone" => Ok(AreaType::Cone),
// "cube" => Ok(AreaType::Cube),
// "cylinder" => Ok(AreaType::Cylinder),
// "line" => Ok(AreaType::Line),
// "sphere" => Ok(AreaType::Sphere),
// _ => Err(())
// }
// }
// }
#[derive(Debug, Serialize, Deserialize)]
pub struct Duration {
#[serde(rename = "type")]
pub duration_type: DurationType,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<String>
}
#[derive(Debug, Serialize, Deserialize)]
pub enum DurationType {
#[serde(rename = "concentration")]
Concentration,
#[serde(rename = "instantaneous")]
Instantaneous,
#[serde(rename = "timed")]
Timed,
#[serde(rename = "dispelled")]
UntilDispelled,
#[serde(rename = "special")]
Special
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Source {
pub source: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<i32>
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Description {
pub entries: Vec<Entry>
}
#[derive(Debug)]
pub struct Entry {
pub entry_type: String,
pub items: Vec<String>
}
impl<'de> Deserialize<'de> for Entry {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
let value = serde_json::Value::deserialize(deserializer)?;
match value {
serde_json::Value::String(s) => Ok(Entry {
entry_type: "string".to_string(),
items: vec![s]
}),
serde_json::Value::Object(o) => {
let entry_type = match o.get("type") {
Some(t) => match t.as_str() {
Some(s) => s.to_string(),
None => return Err(serde::de::Error::custom("Invalid entry type"))
},
None => return Err(serde::de::Error::custom("Missing entry type"))
};
let items = match o.get("items") {
Some(i) => match i.as_array() {
Some(a) => {
let mut items = Vec::new();
for item in a {
match item.as_str() {
Some(s) => items.push(s.to_string()),
None => return Err(serde::de::Error::custom("Invalid entry item"))
}
}
items
},
None => return Err(serde::de::Error::custom("Invalid entry items"))
},
None => return Err(serde::de::Error::custom("Missing entry items"))
};
Ok(Entry {
entry_type,
items
})
},
_ => Err(serde::de::Error::custom("Invalid entry"))
}
}
}
impl Serialize for Entry {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
match self.entry_type.as_str() {
"string" => serializer.serialize_str(&self.items[0]),
_ => {
let mut map = serializer.serialize_map(Some(2))?;
map.serialize_entry("type", &self.entry_type)?;
map.serialize_entry("items", &self.items)?;
map.end()
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Components {
pub verbal: bool,
pub somatic: bool,
pub material: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub materials_needed: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub materials_cost: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub materials_consumed: Option<bool>
}

View File

@@ -0,0 +1,3 @@
mod model;
pub use model::*;

View File

@@ -0,0 +1,3 @@
pub struct User {
pub id: i32
}