From 3021943dd71aa4818496567f38e8ea30eb4a661e Mon Sep 17 00:00:00 2001 From: Nakamura Shuta Date: Wed, 30 Aug 2023 19:47:47 +0900 Subject: [PATCH 1/2] chore:fix d1 Example Usage --- README.md | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 3f0cbcbb3..47d9e8978 100644 --- a/README.md +++ b/README.md @@ -10,31 +10,32 @@ Read the [Notes and FAQ](#notes-and-faq) ```rust use worker::*; +use serde::{Serialize, Deserialize}; -#[event(fetch)] -pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result { - console_log!( - "{} {}, located at: {:?}, within: {}", - req.method().to_string(), - req.path(), - req.cf().coordinates().unwrap_or_default(), - req.cf().region().unwrap_or("unknown region".into()) - ); - - if !matches!(req.method(), Method::Post) { - return Response::error("Method Not Allowed", 405); - } - if let Some(file) = req.form_data().await?.get("file") { - return match file { - FormEntry::File(buf) => { - Response::ok(&format!("size = {}", buf.bytes().await?.len())) - } - _ => Response::error("`file` part of POST form must be a file", 400), - }; - } +#[derive(Serialize, Deserialize)] +struct Thing { + thing_id: String, + desc: String, + num: u32, +} - Response::error("Bad Request", 400) +#[event(fetch, respond_with_errors)] +pub async fn main(request: Request, env: Env, _ctx: Context) -> Result { + Router::new() + .get_async("/:id", |_, ctx| async move { + let id = ctx.param("id").unwrap(); + let d1 = ctx.env.d1("things-db")?; + let statement = d1.prepare("SELECT * FROM things WHERE thing_id = ?1"); + let query = statement.bind(&[id.into()])?; + let result = query.first::(None).await?; + match result { + Some(thing) => Response::from_json(&thing), + None => Response::error("Not found", 404), + } + }) + .run(request, env) + .await } ``` From 0a64f874f2e129aab54ac5e87d97dd80695a2bb9 Mon Sep 17 00:00:00 2001 From: "nakamura.shuta@classmethod.jp" Date: Wed, 13 Sep 2023 10:25:17 +0900 Subject: [PATCH 2/2] fix typo and remarks. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 47d9e8978..f2362ca4e 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,9 @@ pub async fn main(request: Request, env: Env, _ctx: Context) -> Result .get_async("/:id", |_, ctx| async move { let id = ctx.param("id").unwrap(); let d1 = ctx.env.d1("things-db")?; - let statement = d1.prepare("SELECT * FROM things WHERE thing_id = ?1"); + let statement = d1.prepare("SELECT * FROM things WHERE thing_id = ? LIMIT 1"); let query = statement.bind(&[id.into()])?; - let result = query.first::(None).await?; + let result: Option = query.first(None).await?; match result { Some(thing) => Response::from_json(&thing), None => Response::error("Not found", 404),