morethantext-web/src/lib.rs

99 lines
2.0 KiB
Rust

use async_graphql::{EmptySubscription, Object, Result, Schema};
use serde_json;
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()
}
}
struct Query;
#[Object]
impl Query {
async fn pointless(&self) -> String {
"this is pointless.".to_string()
}
//async fn create_table(&self, name: String) -> Result<Option<Table>> {
// Ok(Some(Table::new(name).await))
//}
}
struct Mutation;
#[Object]
impl Mutation {
async fn create_table(&self, name: String) -> Result<Option<Table>> {
Ok(Some(Table::new(name).await))
}
}
#[derive(Clone)]
pub struct Database {
schema: Schema<Query, Mutation, EmptySubscription>,
}
impl Database {
pub fn new() -> Self {
Self {
schema: Schema::new(Query, Mutation, EmptySubscription),
}
}
pub async fn execute(&self, qry: &str) -> String {
let res = self.schema.execute(qry).await;
serde_json::to_string(&res).unwrap()
}
}
#[cfg(test)]
mod queries {
use super::*;
#[async_std::test]
async fn working() {
let db = Database::new();
let output = db.execute("{pointless}").await;
let expected = r#"{"data":{"pointless":"this is pointless."}}"#;
assert!(
output == expected,
"Got '{}' instead of '{}'.",
output,
expected
)
}
}
#[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
)
}
}