diff --git a/src/routes.rs b/src/routes.rs index cf9981e..adf8d18 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -27,9 +27,10 @@ pub(crate) async fn post_create(req: Request, ctx: RouteContext<()>) -> Result id, + Err(e) => return views::create_error(e), + }; views::create_success(target, new_id) } diff --git a/src/store.rs b/src/store.rs index a0a7837..a4eebc9 100644 --- a/src/store.rs +++ b/src/store.rs @@ -27,6 +27,16 @@ pub(crate) async fn create_new_target(ctx: &RouteContext<()>, target: &Target) - None => gen_unused_id(&kv).await.expect("could not generate new id"), }; + if kv + .get(&new_id) + .text() + .await + .expect("couldn't get") + .is_some() + { + return Err("ID Already Exists! Choose another.".into()); + } + console_log!("creating new target with id={}: {:?}", new_id, target); kv.put(&new_id, target.clone()) .expect("couldn't put new target") diff --git a/src/views.rs b/src/views.rs index 40f76f4..3c35362 100644 --- a/src/views.rs +++ b/src/views.rs @@ -1,4 +1,4 @@ -use worker::{Response, Result}; +use worker::{Error, Response, Result}; use crate::{util::serve_html, Stats, Target}; @@ -32,3 +32,14 @@ pub(crate) fn create_success(target: Target, id: String) -> Result { let html = format!(include_str!("./public/layout.html"), body); serve_html(html.as_str()) } + +pub(crate) fn create_error(error: Error) -> Result { + let body = format!( + "

Error creating new tracked URL

+ Try again +

{}

", + error.to_string() + ); + let html = format!(include_str!("./public/layout.html"), body); + serve_html(html.as_str()) +}