95 lines
1.9 KiB
Rust
Raw Normal View History

2022-06-30 23:56:40 -04:00
use async_graphql::{EmptySubscription, Object, Result, Schema};
2022-06-30 08:37:27 -04:00
use serde_json;
2022-06-30 23:56:40 -04:00
struct Table {
name: String,
}
impl Table {
async fn new(name: String) -> Self {
Self { name: name }
}
}
#[Object]
impl Table {
async fn name(&self) -> String {
self.name.to_string()
}
}
2022-06-30 08:37:27 -04:00
struct Query;
#[Object]
impl Query {
async fn pointless(&self) -> String {
"this is pointless.".to_string()
}
2022-06-30 23:56:40 -04:00
}
struct Mutation;
#[Object]
impl Mutation {
async fn create_table(&self, name: String) -> Result<Option<Table>> {
Ok(Some(Table::new(name).await))
}
2022-06-30 08:37:27 -04:00
}
#[derive(Clone)]
2022-06-30 08:37:27 -04:00
pub struct Database {
2022-06-30 23:56:40 -04:00
schema: Schema<Query, Mutation, EmptySubscription>,
2022-06-30 08:37:27 -04:00
}
impl Database {
pub fn new() -> Self {
2022-06-30 08:37:27 -04:00
Self {
2022-06-30 23:56:40 -04:00
schema: Schema::new(Query, Mutation, EmptySubscription),
2022-06-30 08:37:27 -04:00
}
}
2022-06-27 12:15:12 -04:00
2022-06-30 08:37:27 -04:00
pub async fn execute(&self, qry: &str) -> String {
let res = self.schema.execute(qry).await;
serde_json::to_string(&res).unwrap()
2022-06-27 12:15:12 -04:00
}
}
#[cfg(test)]
mod queries {
use super::*;
#[async_std::test]
2022-06-30 08:37:27 -04:00
async fn working() {
let db = Database::new();
let output = db.execute("{pointless}").await;
let expected = r#"{"data":{"pointless":"this is pointless."}}"#;
2022-06-27 12:15:12 -04:00
assert!(
output == expected,
2022-06-30 08:37:27 -04:00
"Got '{}' instead of '{}'.",
2022-06-27 12:15:12 -04:00
output,
expected
2022-06-30 08:37:27 -04:00
)
2022-06-27 12:15:12 -04:00
}
}
2022-06-30 23:56:40 -04:00
#[cfg(test)]
mod mutations {
use super::*;
#[async_std::test]
async fn add_table() {
let db = Database::new();
let output = db
.execute(r#"mutation {createTable(name: "william"){name}}"#)
.await;
let expected = r#"{"data":{"createTable":{"name":"william"}}}"#;
println!("{}", &db.schema.sdl());
assert!(
output == expected,
"Got '{}' instead of '{}'.",
output,
expected
)
}
}