Skip to content

Commit

Permalink
don't overwrite IDs
Browse files Browse the repository at this point in the history
  • Loading branch information
DrewMcArthur committed Jan 21, 2024
1 parent a245e75 commit 2a26295
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
7 changes: 4 additions & 3 deletions src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ pub(crate) async fn post_create(req: Request, ctx: RouteContext<()>) -> Result<R
return Response::error(e.to_string(), 400);
}

let new_id = create_new_target(&ctx, &target)
.await
.expect("couldn't create target");
let new_id = match create_new_target(&ctx, &target).await {
Ok(id) => id,
Err(e) => return views::create_error(e),
};

views::create_success(target, new_id)
}
Expand Down
10 changes: 10 additions & 0 deletions src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
13 changes: 12 additions & 1 deletion src/views.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use worker::{Response, Result};
use worker::{Error, Response, Result};

use crate::{util::serve_html, Stats, Target};

Expand Down Expand Up @@ -32,3 +32,14 @@ pub(crate) fn create_success(target: Target, id: String) -> Result<Response> {
let html = format!(include_str!("./public/layout.html"), body);
serve_html(html.as_str())
}

pub(crate) fn create_error(error: Error) -> Result<Response> {
let body = format!(
"<h1>Error creating new tracked URL</h1>
<a href=\"/create\">Try again</a>
<p class=\"error\">{}</p>",
error.to_string()
);
let html = format!(include_str!("./public/layout.html"), body);
serve_html(html.as_str())
}

0 comments on commit 2a26295

Please sign in to comment.