Skip to content

Commit

Permalink
Fix sys id camel case + clean up (#411)
Browse files Browse the repository at this point in the history
  • Loading branch information
broody authored Jun 3, 2023
1 parent d70f9c4 commit 3ae23da
Show file tree
Hide file tree
Showing 13 changed files with 105 additions and 163 deletions.
67 changes: 0 additions & 67 deletions crates/torii/src/graphql/base.graphql

This file was deleted.

68 changes: 2 additions & 66 deletions crates/torii/src/graphql/mod.rs
Original file line number Diff line number Diff line change
@@ -1,70 +1,6 @@
pub mod component;
pub mod constants;
pub mod entity;
pub mod event;
mod constants;
mod object;
pub mod schema;
pub mod server;
pub mod storage;
pub mod system;
pub mod system_call;

mod types;
mod utils;

use async_graphql::dynamic::{Field, FieldFuture, Object, TypeRef, Union};
use async_graphql::{Name, Value};
use indexmap::IndexMap;

// Type aliases for GraphQL fields
pub type TypeMapping = IndexMap<Name, String>;
pub type ValueMapping = IndexMap<Name, Value>;

pub trait ObjectTrait {
fn name(&self) -> &str;
fn type_name(&self) -> &str;
fn field_type_mapping(&self) -> &TypeMapping;
fn resolvers(&self) -> Vec<Field>;
fn nested_fields(&self) -> Option<Vec<Field>> {
None
}
fn unions(&self) -> Option<Vec<Union>> {
None
}

// Create a new GraphQL object
fn object(&self) -> Object {
let mut object = Object::new(self.type_name());

// Add fields (ie id, createdAt, etc)
for (field_name, field_type) in self.field_type_mapping() {
let field = create_field(field_name, field_type);
object = object.field(field);
}

// Add related fields (ie event, system)
if let Some(nested_fields) = self.nested_fields() {
for field in nested_fields {
object = object.field(field);
}
}

object
}
}

fn create_field(name: &str, field_type: &str) -> Field {
let outer_name = name.to_owned();

Field::new(name, TypeRef::named_nn(field_type), move |ctx| {
let inner_name = outer_name.to_owned();

FieldFuture::new(async move {
let mapping = ctx.parent_value.try_downcast_ref::<ValueMapping>()?;

match mapping.get(inner_name.as_str()) {
Some(value) => Ok(Some(value.clone())),
_ => Err("field not found".into()),
}
})
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use sqlx::pool::PoolConnection;
use sqlx::{FromRow, Pool, Result, Sqlite};

use super::storage::{storage_by_column, type_mapping_from_definition, ColumnName};
use super::types::ScalarType;
use super::utils::extract_value::extract;
use super::utils::{format_name, remove_quotes};
use super::{ObjectTrait, TypeMapping, ValueMapping};
use crate::graphql::types::ScalarType;
use crate::graphql::utils::extract_value::extract;
use crate::graphql::utils::{format_name, remove_quotes};

#[derive(FromRow, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use serde::Deserialize;
use sqlx::pool::PoolConnection;
use sqlx::{FromRow, Pool, Result, Sqlite};

use super::types::ScalarType;
use super::utils::remove_quotes;
use super::{ObjectTrait, TypeMapping, ValueMapping};
use crate::graphql::types::ScalarType;
use crate::graphql::utils::remove_quotes;

#[derive(FromRow, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use sqlx::pool::PoolConnection;
use sqlx::{FromRow, Pool, Result, Sqlite};

use super::system_call::system_call_by_id;
use super::types::ScalarType;
use super::utils::extract_value::extract;
use super::utils::remove_quotes;
use super::{ObjectTrait, TypeMapping, ValueMapping};
use crate::graphql::types::ScalarType;
use crate::graphql::utils::extract_value::extract;
use crate::graphql::utils::remove_quotes;

#[derive(FromRow, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down
64 changes: 64 additions & 0 deletions crates/torii/src/graphql/object/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
pub mod component;
pub mod entity;
pub mod event;
pub mod storage;
pub mod system;
pub mod system_call;

use async_graphql::dynamic::{Field, FieldFuture, Object, TypeRef, Union};
use async_graphql::{Name, Value};
use indexmap::IndexMap;

// Type aliases for GraphQL fields
pub type TypeMapping = IndexMap<Name, String>;
pub type ValueMapping = IndexMap<Name, Value>;

pub trait ObjectTrait {
fn name(&self) -> &str;
fn type_name(&self) -> &str;
fn field_type_mapping(&self) -> &TypeMapping;
fn resolvers(&self) -> Vec<Field>;
fn nested_fields(&self) -> Option<Vec<Field>> {
None
}
fn unions(&self) -> Option<Vec<Union>> {
None
}

// Create a new GraphQL object
fn object(&self) -> Object {
let mut object = Object::new(self.type_name());

// Add fields (ie id, createdAt, etc)
for (field_name, field_type) in self.field_type_mapping() {
let field = create_field(field_name, field_type);
object = object.field(field);
}

// Add related fields (ie event, system)
if let Some(nested_fields) = self.nested_fields() {
for field in nested_fields {
object = object.field(field);
}
}

object
}
}

fn create_field(name: &str, field_type: &str) -> Field {
let outer_name = name.to_owned();

Field::new(name, TypeRef::named_nn(field_type), move |ctx| {
let inner_name = outer_name.to_owned();

FieldFuture::new(async move {
let mapping = ctx.parent_value.try_downcast_ref::<ValueMapping>()?;

match mapping.get(inner_name.as_str()) {
Some(value) => Ok(Some(value.clone())),
_ => Err("field not found".into()),
}
})
})
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ fn value_mapping_from_row(row: &SqliteRow, fields: &TypeMapping) -> Result<Value
}
_ => return Err(Error::TypeNotFound { type_name: field_type.clone() }),
};
value_mapping.insert(field_name.clone(), value);

value_mapping.insert(Name::new(field_name), value);
}

Ok(value_mapping)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use sqlx::pool::PoolConnection;
use sqlx::{FromRow, Pool, Result, Sqlite};

use super::system_call::system_calls_by_system_id;
use super::types::ScalarType;
use super::utils::extract_value::extract;
use super::utils::remove_quotes;
use super::{ObjectTrait, TypeMapping, ValueMapping};
use crate::graphql::types::ScalarType;
use crate::graphql::utils::extract_value::extract;
use crate::graphql::utils::remove_quotes;

#[derive(FromRow, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ use serde::Deserialize;
use sqlx::pool::PoolConnection;
use sqlx::{FromRow, Pool, Result, Sqlite};

// use super::system::System;
use super::system::system_by_id;
use super::types::ScalarType;
use super::utils::extract_value::extract;
use super::{ObjectTrait, TypeMapping, ValueMapping};
use crate::graphql::types::ScalarType;
use crate::graphql::utils::extract_value::extract;

#[derive(FromRow, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand All @@ -32,7 +31,7 @@ impl SystemCallObject {
(Name::new("id"), TypeRef::ID.to_string()),
(Name::new("transactionHash"), TypeRef::STRING.to_string()),
(Name::new("data"), TypeRef::STRING.to_string()),
(Name::new("system_id"), TypeRef::ID.to_string()),
(Name::new("systemId"), TypeRef::ID.to_string()),
(Name::new("createdAt"), ScalarType::DATE_TIME.to_string()),
]),
}
Expand Down Expand Up @@ -106,7 +105,7 @@ fn value_mapping(system_call: SystemCall) -> ValueMapping {
(Name::new("id"), Value::from(system_call.id.to_string())),
(Name::new("transactionHash"), Value::from(system_call.transaction_hash)),
(Name::new("data"), Value::from(system_call.data)),
(Name::new("system_id"), Value::from(system_call.system_id)),
(Name::new("systemId"), Value::from(system_call.system_id)),
(
Name::new("createdAt"),
Value::from(system_call.created_at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
Expand Down
14 changes: 7 additions & 7 deletions crates/torii/src/graphql/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ use anyhow::Result;
use async_graphql::dynamic::{Object, Scalar, Schema};
use sqlx::SqlitePool;

use super::component::{Component, ComponentObject};
use super::entity::EntityObject;
use super::event::EventObject;
use super::storage::{type_mapping_from_definition, StorageObject};
use super::system::SystemObject;
use super::system_call::SystemCallObject;
use super::object::component::{Component, ComponentObject};
use super::object::entity::EntityObject;
use super::object::event::EventObject;
use super::object::storage::{type_mapping_from_definition, StorageObject};
use super::object::system::SystemObject;
use super::object::system_call::SystemCallObject;
use super::object::ObjectTrait;
use super::types::ScalarType;
use super::utils::format_name;
use super::ObjectTrait;

pub async fn build_schema(pool: &SqlitePool) -> Result<Schema> {
let mut schema_builder = Schema::build("Query", None, None);
Expand Down
2 changes: 1 addition & 1 deletion crates/torii/src/graphql/utils/extract_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::borrow::Cow;
use async_graphql::Result;

use super::value_accessor::{ObjectAccessor, ValueAccessor};
use crate::graphql::ValueMapping;
use crate::graphql::object::ValueMapping;

pub trait ExtractValue: Sized {
fn extract(value_accessor: ValueAccessor<'_>) -> Result<Self>;
Expand Down
10 changes: 7 additions & 3 deletions crates/torii/src/tests/entities_test.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
#[cfg(test)]
mod tests {
use serde::Deserialize;
use sqlx::SqlitePool;

use crate::graphql::entity::Entity;
use crate::tests::common::run_graphql_query;

#[derive(Deserialize)]
pub struct Entity {
pub id: String,
}

#[sqlx::test(migrations = "./migrations", fixtures("entities"))]
async fn test_entity(pool: SqlitePool) {
let _ = pool.acquire().await;

let query =
"{ entity(id: \"entity_1\") { id name partitionId keys transactionHash createdAt } }";
let query = "{ entity(id: \"entity_1\") { id } }";
let value = run_graphql_query(&pool, query).await;

let entity = value.get("entity").ok_or("no entity found").unwrap();
Expand Down
9 changes: 7 additions & 2 deletions crates/torii/src/tests/events_test.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
#[cfg(test)]
mod tests {
use serde::Deserialize;
use sqlx::SqlitePool;

use crate::graphql::event::Event;
use crate::tests::common::run_graphql_query;

#[derive(Deserialize)]
pub struct Event {
pub id: String,
}

#[sqlx::test(migrations = "./migrations", fixtures("systems", "system_calls", "events"))]
async fn test_event(pool: SqlitePool) {
let _ = pool.acquire().await;

let query = "{ event(id: \"event_1\") { id keys data systemCallId createdAt } }";
let query = "{ event(id: \"event_1\") { id } }";
let value = run_graphql_query(&pool, query).await;

let event = value.get("event").ok_or("no event found").unwrap();
Expand Down

0 comments on commit 3ae23da

Please sign in to comment.