No duplicate tables.
This commit is contained in:
		
							
								
								
									
										26
									
								
								src/lib.rs
									
									
									
									
									
								
							
							
						
						
									
										26
									
								
								src/lib.rs
									
									
									
									
									
								
							@@ -1,4 +1,4 @@
 | 
			
		||||
use async_graphql::{Context, EmptySubscription, Object, Result, Schema};
 | 
			
		||||
use async_graphql::{Context, EmptySubscription, Error, Object, Result, Schema};
 | 
			
		||||
use async_std::sync::RwLock;
 | 
			
		||||
use serde_json;
 | 
			
		||||
 | 
			
		||||
@@ -52,10 +52,15 @@ struct Mutation;
 | 
			
		||||
impl Mutation {
 | 
			
		||||
    async fn create_table(&self, ctx: &Context<'_>, name: String) -> Result<Option<Table>> {
 | 
			
		||||
        let mut tables = ctx.data::<RwLock<Vec<Table>>>().unwrap().write().await;
 | 
			
		||||
        let output = Table::new(name).await;
 | 
			
		||||
        tables.push(output.clone());
 | 
			
		||||
        tables.sort_by_key(|k| k.name.clone());
 | 
			
		||||
        Ok(Some(output))
 | 
			
		||||
        match tables.binary_search_by(|t| t.name.cmp(&name)) {
 | 
			
		||||
            Ok(_) => Err(Error::new(format!("Table {} already exists.", &name))),
 | 
			
		||||
            Err(_) => {
 | 
			
		||||
                let output = Table::new(name).await;
 | 
			
		||||
                tables.push(output.clone());
 | 
			
		||||
                tables.sort_by_key(|k| k.name.clone());
 | 
			
		||||
                Ok(Some(output))
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@@ -143,7 +148,16 @@ mod mutations {
 | 
			
		||||
            .execute(r#"mutation {createTable(name: "william"){name}}"#)
 | 
			
		||||
            .await;
 | 
			
		||||
        let expected = r#"{"data":{"createTable":{"name":"william"}}}"#;
 | 
			
		||||
        println!("{}", &db.schema.sdl());
 | 
			
		||||
        support::compare(&db, &output, &expected);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    #[async_std::test]
 | 
			
		||||
    async fn cannot_add_duplicate_table() {
 | 
			
		||||
        let db = Database::new();
 | 
			
		||||
        let qry = r#"mutation {createTable(name: "gadzoo"){name}}"#;
 | 
			
		||||
        db.execute(&qry).await;
 | 
			
		||||
        let output = db.execute(qry).await;
 | 
			
		||||
        let expected = r#"{"data":null,"errors":[{"message":"Table gadzoo already exists.","locations":[{"line":1,"column":11}],"path":["createTable"]}]}"#;
 | 
			
		||||
        support::compare(&db, &output, &expected);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user