From 9ebc7bef5eeee4220a126acf39fbd800cb99894f Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Fri, 1 Jul 2022 12:03:47 -0400 Subject: [PATCH] Added a tables listing. --- src/lib.rs | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 2956661..1f8dfe5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,8 @@ -use async_graphql::{EmptySubscription, Object, Result, Schema}; +use async_graphql::{Context, EmptySubscription, Object, Result, Schema}; +use async_std::sync::RwLock; use serde_json; +#[derive(Clone)] struct Table { name: String, } @@ -25,14 +27,25 @@ impl Query { async fn pointless(&self) -> String { "this is pointless.".to_string() } + + async fn tables(&self, ctx: &Context<'_>) -> Vec { + ctx.data::>>() + .unwrap() + .read() + .await + .to_vec() + } } struct Mutation; #[Object] impl Mutation { - async fn create_table(&self, name: String) -> Result> { - Ok(Some(Table::new(name).await)) + async fn create_table(&self, ctx: &Context<'_>, name: String) -> Result> { + let mut tables = ctx.data::>>().unwrap().write().await; + let output = Table::new(name).await; + tables.push(output.clone()); + Ok(Some(output)) } } @@ -43,8 +56,11 @@ pub struct Database { impl Database { pub fn new() -> Self { + let tables: Vec
= Vec::new(); Self { - schema: Schema::new(Query, Mutation, EmptySubscription), + schema: Schema::build(Query, Mutation, EmptySubscription) + .data(RwLock::new(tables)) + .finish(), } } @@ -70,6 +86,24 @@ mod queries { expected ) } + + #[async_std::test] + async fn list_tables() { + let db = Database::new(); + db.execute(r#"mutation {createTable(name: "fred"){name}}"#) + .await; + db.execute(r#"mutation {createTable(name: "barney"){name}}"#) + .await; + let output = db.execute(r#"{tables{name}}"#).await; + let expected = r#"{"data":{"tables":[{"name":"fred"},{"name":"barney"}]}}"#; + assert!( + output == expected, + "\n\n{}\nGot: {}\nWant: {}\n\n", + &db.schema.sdl(), + output, + expected + ); + } } #[cfg(test)]