Added html
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2022-08-15 22:55:04 +02:00
parent 59d33034df
commit e4b1f79a61
16 changed files with 1577 additions and 103 deletions

View File

@@ -1,67 +0,0 @@
use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema, SimpleObject};
use uuid::Uuid;
pub type CibusSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
pub struct QueryRoot;
#[Object]
impl QueryRoot {
async fn get_upcoming(&self, ctx: &Context<'_>) -> Vec<Event> {
vec![Event::new(
None,
"Some-name".into(),
None,
None,
EventDate::new(2022, 08, 08, 23, 51),
)]
}
}
#[derive(SimpleObject)]
pub struct Event {
pub id: String,
pub name: String,
pub description: Option<Vec<String>>,
pub location: Option<String>,
pub date: EventDate,
}
impl Event {
pub fn new(
id: Option<String>,
name: String,
description: Option<Vec<String>>,
location: Option<String>,
date: EventDate,
) -> Self {
Self {
id: id.unwrap_or_else(|| Uuid::new_v4().to_string()),
name,
description,
location,
date,
}
}
}
#[derive(SimpleObject)]
pub struct EventDate {
pub year: u32,
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
}
impl EventDate {
pub fn new(year: u32, month: u32, day: u32, hour: u32, minute: u32) -> Self {
Self {
year,
month,
day,
hour,
minute,
}
}
}

View File

@@ -1,52 +1,52 @@
mod graphql;
use std::env::{self, current_dir};
use std::env;
use async_graphql::{
http::{playground_source, GraphQLPlaygroundConfig},
EmptyMutation, EmptySubscription, Request, Response, Schema,
};
use askama::Template;
use axum::{
extract::Extension,
response::{Html, IntoResponse},
routing::get,
Json, Router,
http::StatusCode,
response::{Html, IntoResponse, Response},
routing::{get, get_service},
Router,
};
use graphql::{CibusSchema, QueryRoot};
use axum_extra::routing::SpaRouter;
use sqlx::PgPool;
async fn graphql_handler(schema: Extension<CibusSchema>, req: Json<Request>) -> Json<Response> {
schema.execute(req.0).await.into()
}
async fn graphql_playground() -> impl IntoResponse {
Html(playground_source(GraphQLPlaygroundConfig::new("/")))
}
use tower_http::{services::ServeDir, trace::TraceLayer};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Environment
println!("Loading dotenv");
tracing::info!("Loading dotenv");
dotenv::dotenv()?;
// Logging
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| {
"cibus_bin=debug,tower_http=debug,axum_extra=debug,hyper=info,mio=info".into()
}),
))
.with(tracing_subscriber::fmt::layer())
.init();
// Database
println!("Creating pool");
let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
tracing::info!("Creating pool");
let db_url = env::var("DATABASE_URL")?;
let pool = PgPool::connect(&db_url).await?;
// Database Migrate
println!("Migrating db");
tracing::info!("Migrating db");
sqlx::migrate!("db/migrations").run(&pool).await?;
tracing::info!("current path: {}", current_dir()?.to_string_lossy());
// Webserver
println!("Building schema");
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription).finish();
println!("Building router");
tracing::info!("Building router");
let app = Router::new()
.route("/", get(graphql_playground).post(graphql_handler))
.layer(Extension(schema));
.route("/", get(index_handler))
.merge(SpaRouter::new("/assets", "assets"))
.layer(TraceLayer::new_for_http());
println!("Starting webserver");
tracing::info!("Starting webserver");
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
@@ -54,3 +54,33 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
struct HtmlTemplate<T>(T);
impl<T> IntoResponse for HtmlTemplate<T>
where
T: Template,
{
fn into_response(self) -> Response {
match self.0.render() {
Ok(html) => Html(html).into_response(),
Err(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to render template. Error: {}", err),
)
.into_response(),
}
}
}
#[derive(Template)]
#[template(path = "index.html")]
struct IndexTemplate {
name: String,
}
async fn index_handler() -> impl IntoResponse {
HtmlTemplate(IndexTemplate {
name: "Cibus".into(),
})
}