Updated spells schema

This commit is contained in:
Benjamin Sherriff
2023-10-03 21:00:14 -04:00
parent 16d8fa5af8
commit 75a71410a5
13 changed files with 890 additions and 143 deletions

View File

@@ -6,38 +6,40 @@ pub use routes::init_routes;
pub fn load_data() {
let root_path = std::env::current_dir().unwrap();
let mut data_path = std::path::PathBuf::from(root_path);
data_path.push("data/spells.json");
match data_path.to_str() {
Some(path) => {
log::debug!("Loading spells from {}", path);
match std::fs::read_to_string(data_path) {
Ok(data) => {
match serde_json::from_str::<serde_json::Value>(&data) {
Ok(json) => {
match serde_json::from_value::<Vec<Spell>>(json) {
Ok(spells) => {
let count = QuerySpell::get_count().unwrap();
if count >= spells.len() as i64 {
log::warn!("Spell data is already loaded");
return;
}
for spell in spells {
match InsertSpell::insert(spell.into()) {
Ok(_) => {},
Err(err) => log::error!("Failed to insert spell: {}", err)
}
}
},
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 spells data: {}", err)
};
},
None => log::error!("Failed to find spells data directory")
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().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

@@ -1,7 +1,9 @@
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use std::str::FromStr;
use crate::{db::schema::spells, error_handler::ServiceError};
use diesel::prelude::*;
use serde::{Deserialize, Serialize, ser::SerializeMap};
use crate::{db::{schema::spells, classes::AbilityType, conditions::ConditionType}, error_handler::ServiceError};
#[derive(Queryable, QueryableByName)]
#[diesel(table_name = spells)]
@@ -11,17 +13,31 @@ pub struct QuerySpell {
pub school: String,
pub level: i32,
pub ritual: bool,
pub casting_time: String,
pub range: String,
pub casting_time_amount: i32,
pub casting_time_unit: String,
pub saving_throw: Option<Vec<String>>,
pub attack_type: Option<String>,
pub damage_type: Option<String>,
pub conditions: Option<Vec<String>>,
pub range_type: String,
pub range_amount: Option<i32>,
pub range_unit: Option<String>,
pub area_type: Option<String>,
pub area_amount: Option<i32>,
pub area_unit: Option<String>,
pub components_verbal: bool,
pub components_somatic: bool,
pub components_material: bool,
pub components_materials_needed: Option<String>,
pub duration: String,
pub components_materials_cost: Option<i32>,
pub components_materials_consumed: Option<bool>,
pub duration_type: String,
pub duration_amount: Option<i32>,
pub duration_unit: Option<String>,
pub classes: Vec<String>,
pub sources: Vec<String>,
pub tags: Vec<String>,
pub description: String
pub description: serde_json::Value
}
impl QuerySpell {
@@ -63,17 +79,31 @@ pub struct InsertSpell {
pub school: String,
pub level: i32,
pub ritual: bool,
pub casting_time: String,
pub range: String,
pub casting_time_amount: i32,
pub casting_time_unit: String,
pub saving_throw: Option<Vec<String>>,
pub attack_type: Option<String>,
pub damage_type: Option<String>,
pub conditions: Option<Vec<String>>,
pub range_type: String,
pub range_amount: Option<i32>,
pub range_unit: Option<String>,
pub area_type: Option<String>,
pub area_amount: Option<i32>,
pub area_unit: Option<String>,
pub components_verbal: bool,
pub components_somatic: bool,
pub components_material: bool,
pub components_materials_needed: Option<String>,
pub duration: String,
pub components_materials_cost: Option<i32>,
pub components_materials_consumed: Option<bool>,
pub duration_type: String,
pub duration_amount: Option<i32>,
pub duration_unit: Option<String>,
pub classes: Vec<String>,
pub sources: Vec<String>,
pub tags: Vec<String>,
pub description: String
pub description: serde_json::Value
}
impl InsertSpell {
@@ -90,50 +120,541 @@ impl InsertSpell {
}
}
#[derive(Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize)]
pub struct Spell {
pub name: String,
pub school: String,
pub school: SchoolType,
pub level: i32,
pub ritual: bool,
pub casting_time: String,
pub range: String,
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_type: Option<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 duration: String,
pub duration: Duration,
pub classes: Vec<String>,
pub sources: Vec<String>,
pub tags: Vec<String>,
pub description: 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>
}
#[derive(Serialize, Deserialize)]
#[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 = "type")]
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
}
impl DurationType {
pub fn to_string(&self) -> String {
match self {
DurationType::Concentration => "concentration".to_string(),
DurationType::Instantaneous => "instantaneous".to_string(),
DurationType::Timed => "timed".to_string(),
DurationType::UntilDispelled => "dispelled".to_string(),
DurationType::Special => "special".to_string()
}
}
}
impl FromStr for DurationType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"concentration" => Ok(DurationType::Concentration),
"instantaneous" => Ok(DurationType::Instantaneous),
"timed" => Ok(DurationType::Timed),
"dispelled" => Ok(DurationType::UntilDispelled),
"special" => Ok(DurationType::Special),
_ => Err(())
}
}
}
#[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,
pub materials_needed: Option<String>
#[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>
}
impl From<QuerySpell> for Spell {
fn from(query: QuerySpell) -> Self {
return Self {
name: query.name,
school: query.school,
school: match SchoolType::from_str(&query.school) {
Ok(school_type) => school_type,
Err(_) => {
log::error!("Failed to parse spell school type: {}", query.school);
SchoolType::Abjuration
}
},
level: query.level,
ritual: query.ritual,
casting_time: query.casting_time,
range: query.range,
casting_time: CastingTime {
amount: query.casting_time_amount,
casting_type: match CastingType::from_str(&query.casting_time_unit) {
Ok(casting_type) => casting_type,
Err(_) => {
log::error!("Failed to parse spell casting type: {}", query.casting_time_unit);
CastingType::Action
}
}
},
saving_throw: query.saving_throw.map(|saving_throw| saving_throw.iter().map(|ability_type| match AbilityType::from_str(&ability_type) {
Ok(ability_type) => ability_type,
Err(_) => {
log::error!("Failed to parse spell saving throw: {}", ability_type);
AbilityType::Strength
}
}).collect()),
attack_type: match query.attack_type {
Some(attack_type) => match SpellAttackType::from_str(&attack_type) {
Ok(attack_type) => Some(attack_type),
Err(_) => {
log::error!("Failed to parse spell attack type: {}", attack_type);
None
}
},
None => None
},
damage_type: query.damage_type.map(|damage_type| match SpellDamageType::from_str(&damage_type) {
Ok(damage_type) => damage_type,
Err(_) => {
log::error!("Failed to parse spell damage type: {}", damage_type);
SpellDamageType::Acid
}
}),
conditions: query.conditions.map(|conditions| conditions.iter().map(|condition_type| match ConditionType::from_str(&condition_type) {
Ok(condition_type) => condition_type,
Err(_) => {
log::error!("Failed to parse spell condition type: {}", condition_type);
ConditionType::Blinded
}
}).collect()),
range: Range {
range_type: query.range_type,
amount: query.range_amount,
unit: query.range_unit
},
area: match query.area_type {
Some(area_type) => Some(Area {
area_type: match AreaType::from_str(&area_type) {
Ok(area_type) => area_type,
Err(_) => {
log::error!("Failed to parse spell area type: {}", area_type);
AreaType::Cone
}
},
amount: query.area_amount,
unit: query.area_unit
}),
None => None
},
components: Components {
verbal: query.components_verbal,
somatic: query.components_somatic,
material: query.components_material,
materials_needed: query.components_materials_needed
materials_needed: query.components_materials_needed,
materials_cost: query.components_materials_cost,
materials_consumed: query.components_materials_consumed
},
duration: Duration {
duration_type: match DurationType::from_str(&query.duration_type) {
Ok(duration_type) => duration_type,
Err(_) => {
log::error!("Failed to parse spell duration type: {}", query.duration_type);
DurationType::Special
}
},
amount: query.duration_amount,
unit: query.duration_unit
},
duration: query.duration,
classes: query.classes,
sources: query.sources,
tags: query.tags,
description: query.description
sources: query.sources.iter().map(|source| Source {
source: source.to_string(),
page: None
}).collect(),
tags: Some(query.tags),
description: match serde_json::from_value(query.description) {
Ok(description) => description,
Err(err) => {
log::error!("Failed to parse spell description: {}", err);
None
}
}
}
}
}
@@ -142,20 +663,67 @@ impl Into<InsertSpell> for Spell {
fn into(self) -> InsertSpell {
return InsertSpell {
name: self.name,
school: self.school,
school: self.school.to_string(),
level: self.level,
ritual: self.ritual,
casting_time: self.casting_time,
range: self.range,
casting_time_amount: self.casting_time.amount,
casting_time_unit: self.casting_time.casting_type.to_string(),
saving_throw: match self.saving_throw {
Some(saving_throw) => Some(saving_throw.iter().map(|ability_type| ability_type.to_string()).collect()),
None => None
},
attack_type: match self.attack_type {
Some(attack_type) => Some(attack_type.to_string()),
None => None
},
damage_type: match self.damage_type {
Some(damage_type) => Some(damage_type.to_string()),
None => None
},
conditions: match self.conditions {
Some(conditions) => Some(conditions.iter().map(|condition_type| condition_type.to_string()).collect()),
None => None
},
range_type: self.range.range_type.to_string(),
range_amount: self.range.amount,
range_unit: self.range.unit,
area_type: match &self.area {
Some(area) => Some(area.area_type.to_string()),
None => None
},
area_amount: match &self.area {
Some(area) => area.amount,
None => None
},
area_unit: match &self.area {
Some(area) => match &area.unit {
Some(unit) => Some(unit.to_string()),
None => None
},
None => None
},
components_verbal: self.components.verbal,
components_somatic: self.components.somatic,
components_material: self.components.material,
components_materials_needed: self.components.materials_needed,
duration: self.duration,
components_materials_cost: self.components.materials_cost,
components_materials_consumed: self.components.materials_consumed,
duration_type: self.duration.duration_type.to_string(),
duration_amount: self.duration.amount,
duration_unit: self.duration.unit,
classes: self.classes,
sources: self.sources,
tags: self.tags,
description: self.description
sources: self.sources.iter().map(|source| match source.page { Some(page) => format!("{} {}", source.source, page), None => source.source.to_string() }).collect(),
tags: match self.tags {
Some(tags) => tags,
None => Vec::new()
},
description: match serde_json::to_value(self.description) {
Ok(description) => description,
Err(err) => {
log::error!("Failed to serialize spell description: {}", err);
serde_json::Value::Null
}
}
}
}
}