Skip to content

Commit

Permalink
get panel page working and handle form
Browse files Browse the repository at this point in the history
  • Loading branch information
Joeyh021 committed May 27, 2023
1 parent 330fcc4 commit 5666a02
Show file tree
Hide file tree
Showing 10 changed files with 632 additions and 120 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ edition = "2021"
anyhow = "1.0.71"
askama = { version = "0.12.0", features = ["with-axum"] }
askama_axum = "0.3.0"
axum = { version = "0.6.18", features = ["headers"] }
axum = { version = "0.6.18", features = ["headers", "form"] }
axum-sessions = "0.5.0"
chrono = { version = "0.4.24", features = ["serde"] }
dotenvy = "0.15.7"
Expand Down
24 changes: 2 additions & 22 deletions src/db.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,6 @@
use chrono::serde::ts_seconds_option;
use serde::{Deserialize, Serialize};
use sqlx::{
types::chrono::{DateTime, Utc},
FromRow, PgPool,
};
use sqlx::PgPool;

///Represents a go link, a mapping from source -> sink with some metadata
#[derive(Debug, FromRow, Serialize, Deserialize)]
pub struct Redirect {
pub source: String,
pub sink: String,
///number of times this link has been used
pub usages: i32,

///Last time this link was used. Serialized as seconds since epoch
#[serde(with = "ts_seconds_option")]
pub last_used: Option<DateTime<Utc>>,

///When this link was created. Serialized as seconds since epoch
#[serde(with = "ts_seconds_option")]
pub created: Option<DateTime<Utc>>,
}
use crate::types::*;

/// Gets the redirect URL (sink) for a given source
pub async fn get_sink(source: &str, conn: &PgPool) -> Result<Option<String>, sqlx::Error> {
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use tower_http::services::ServeDir;
mod config;
mod db;
mod routes;
pub use db::Redirect;
mod types;

/// Struct containing application state that may be needed by any handler
#[derive(Debug, Clone)]
Expand Down
12 changes: 3 additions & 9 deletions src/routes/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::collections::HashMap;

use crate::AppState;

use crate::db;
use crate::types::*;
use axum::{
extract::{Query, State},
headers::{authorization::Bearer, Authorization},
Expand All @@ -12,14 +14,6 @@ use axum::{
Json, RequestPartsExt, Router, TypedHeader,
};

use crate::db;

#[derive(Debug, serde::Deserialize)]
struct GoPair {
source: String,
sink: String,
}

#[tracing::instrument]
async fn add_redirect(
State(state): State<AppState>,
Expand All @@ -43,7 +37,7 @@ async fn add_redirect(
async fn get_redirects(
State(state): State<AppState>,
Query(q): Query<HashMap<String, u32>>,
) -> Result<Json<Vec<crate::Redirect>>> {
) -> Result<Json<Vec<Redirect>>> {
tracing::info!("{q:?}");
match match (q.get("limit"), q.get("offset")) {
(Some(limit), Some(offset)) => {
Expand Down
32 changes: 28 additions & 4 deletions src/routes/app.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use super::handle_error;
use crate::AppState;
use crate::{db, types::GoPair, AppState};
use anyhow::Context;
use askama::Template;
use axum::{
extract::State,
http::StatusCode,
response::{IntoResponse, Redirect, Result},
routing::get,
Router,
Form, Router,
};
use axum_sessions::extractors::ReadableSession;
pub async fn home() -> impl IntoResponse {
Expand All @@ -21,7 +22,7 @@ pub async fn home() -> impl IntoResponse {
#[template(path = "app.html")]
struct PanelTemplate {
username: String,
redirects: Vec<crate::db::Redirect>,
redirects: Vec<crate::types::Redirect>,
}

async fn panel(
Expand All @@ -43,7 +44,30 @@ async fn panel(
})
}

async fn handle_form(session: ReadableSession) {}
async fn handle_form(
State(s): State<AppState>,
session: ReadableSession,
Form(f): Form<GoPair>,
) -> Result<impl IntoResponse> {
if session.get::<String>("username").is_none() {
return Err((
StatusCode::UNAUTHORIZED,
"You must be logged in to do that.",
)
.into());
}
db::add_new(&f.source, &f.sink, &s.pool)
.await
.context("Could not add new redirect to database")
.map_err(handle_error)
.map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
"An error occursed while adding your go link to the database.",
)
})?;
Ok(Redirect::to("/app/panel"))
}

pub fn app_routes() -> Router<AppState> {
Router::new().route("/panel", get(panel).post(handle_form))
Expand Down
26 changes: 26 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use chrono::{serde::ts_seconds_option, DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

///Represents a go link, a mapping from source -> sink with some metadata
#[derive(Debug, FromRow, Serialize, Deserialize)]
pub struct Redirect {
pub source: String,
pub sink: String,
///number of times this link has been used
pub usages: i32,

///Last time this link was used. Serialized as seconds since epoch
#[serde(with = "ts_seconds_option")]
pub last_used: Option<DateTime<Utc>>,

///When this link was created. Serialized as seconds since epoch
#[serde(with = "ts_seconds_option")]
pub created: Option<DateTime<Utc>>,
}

#[derive(Debug, serde::Deserialize)]
pub struct GoPair {
pub source: String,
pub sink: String,
}
Loading

0 comments on commit 5666a02

Please sign in to comment.