From c3c79b7529779ebde5f8f8ab71bd1b6daa289d50 Mon Sep 17 00:00:00 2001 From: o-az Date: Sun, 10 Nov 2024 14:09:46 -0800 Subject: [PATCH 1/5] feat: possible improvements --- src/lib.rs | 64 +++++++++++++++++++++++++++++++++------------------- src/utils.rs | 26 +++++++++++++-------- 2 files changed, 57 insertions(+), 33 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3510b67..ce25fe3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +use serde::{Deserialize, Serialize}; use serde_json::Value; use url::Url; use worker::*; @@ -5,6 +6,30 @@ use worker::*; mod utils; use utils::*; +#[derive(Deserialize, Serialize)] +struct Record { + id: u64, + url: String, + created_at: String, +} + +use std::fmt; + +impl fmt::Display for KvError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + KvError::Secret(msg) => write!(f, "Secret error: {}", msg), + KvError::Var(msg) => write!(f, "Var error: {}", msg), + } + } +} + +impl From for worker::Error { + fn from(error: KvError) -> Self { + worker::Error::from(error.to_string()) + } +} + const DEV_ROUTES: [&str; 2] = ["/list", "/env"]; #[event(fetch)] @@ -14,31 +39,24 @@ async fn fetch(request: Request, env: Env, _context: Context) -> Result, ) -> worker::Result { - let d1 = context.env.d1("DB"); - let statement = d1?.prepare("SELECT * FROM urls"); - let query = statement.bind(&[]); - let result = query?.all().await?; + let d1 = context.env.d1("DB")?; + let statement = d1.prepare("SELECT * FROM urls"); + // let query = statement.bind(&[])?; + let result = statement.all().await?; - let urls: Vec = result.results()?; - Response::from_json(&urls) + let records: Vec = result.results()?; + Response::from_json(&records) } diff --git a/src/utils.rs b/src/utils.rs index 41ce5e3..85e1fb5 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,15 +1,21 @@ +use std::result::Result; + use worker::*; -pub fn get_secret(name: &str, env: &Env) -> Option { - match env.secret(name) { - Ok(value) => Some(value.to_string()), - Err(_) => None, - } +#[derive(Debug, Clone, PartialEq)] +pub enum KvError { + Var(String), + Secret(String), +} + +pub fn get_secret(name: &str, env: &Env) -> Result { + env.secret(name) + .map(|value| value.to_string()) + .map_err(|error| KvError::Secret(error.to_string())) } -pub fn get_var(name: &str, env: &Env) -> Option { - match env.var(name) { - Ok(value) => Some(value.to_string()), - Err(_) => None, - } +pub fn get_var(name: &str, env: &Env) -> Result { + env.var(name) + .map(|value| value.to_string()) + .map_err(|error| KvError::Var(error.to_string())) } From ba43f6a799356a1f96aca010bff9221149043d2e Mon Sep 17 00:00:00 2001 From: o-az Date: Wed, 13 Nov 2024 05:52:34 -0800 Subject: [PATCH 2/5] chore: follow clippy advice --- Cargo.lock | 8 +- Cargo.toml | 4 +- flake.lock | 513 ++++++--------------------------------------------- flake.nix | 2 + src/lib.rs | 74 ++++---- src/utils.rs | 21 --- tasks.nix | 2 +- 7 files changed, 101 insertions(+), 523 deletions(-) delete mode 100644 src/utils.rs diff --git a/Cargo.lock b/Cargo.lock index 7f83d82..abcf0db 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -609,9 +609,9 @@ checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" [[package]] name = "serde" -version = "1.0.214" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" +checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" dependencies = [ "serde_derive", ] @@ -640,9 +640,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.214" +version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" +checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 828e11e..7d80c55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,8 @@ edition = "2021" license = "MIT" description = "A URL shortener" repository = "https://github.com/union-labs/url-shortener" +keywords = ["cloudflare", "workers", "rust", "url", "shortener"] +categories = ["web-programming::http-server", "web-programming::websocket"] [package.metadata.release] release = false @@ -18,7 +20,7 @@ crate-type = ["cdylib"] [dependencies] url = "2.5.3" -serde = { version = "1.0.214", features = ["derive"] } +serde = { version = "1.0.215", features = ["derive"] } serde_json = "1.0.104" # needed to enable the "js" feature for compatibility with wasm, # see https://docs.rs/getrandom/#webassembly-support diff --git a/flake.lock b/flake.lock index 6ae8288..b7a226e 100644 --- a/flake.lock +++ b/flake.lock @@ -2,66 +2,28 @@ "nodes": { "cachix": { "inputs": { - "devenv": "devenv_2", - "flake-compat": [ - "devenv", - "flake-compat" - ], - "git-hooks": [ - "devenv", - "pre-commit-hooks" + "devenv": [ + "devenv" ], - "nixpkgs": [ - "devenv", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1726520618, - "narHash": "sha256-jOsaBmJ/EtX5t/vbylCdS7pWYcKGmWOKg4QKUzKr6dA=", - "owner": "cachix", - "repo": "cachix", - "rev": "695525f9086542dfb09fde0871dbf4174abbf634", - "type": "github" - }, - "original": { - "owner": "cachix", - "repo": "cachix", - "type": "github" - } - }, - "cachix_2": { - "inputs": { - "devenv": "devenv_3", "flake-compat": [ - "devenv", - "cachix", - "devenv", - "flake-compat" + "devenv" ], - "nixpkgs": [ - "devenv", - "cachix", - "devenv", - "nixpkgs" + "git-hooks": [ + "devenv" ], - "pre-commit-hooks": [ - "devenv", - "cachix", - "devenv", - "pre-commit-hooks" - ] + "nixpkgs": "nixpkgs" }, "locked": { - "lastModified": 1712055811, - "narHash": "sha256-7FcfMm5A/f02yyzuavJe06zLa9hcMHsagE28ADcmQvk=", + "lastModified": 1728672398, + "narHash": "sha256-KxuGSoVUFnQLB2ZcYODW7AVPAh9JqRlD5BrfsC/Q4qs=", "owner": "cachix", "repo": "cachix", - "rev": "02e38da89851ec7fec3356a5c04bc8349cae0e30", + "rev": "aac51f698309fd0f381149214b7eee213c66ef0a", "type": "github" }, "original": { "owner": "cachix", + "ref": "latest", "repo": "cachix", "type": "github" } @@ -69,92 +31,23 @@ "devenv": { "inputs": { "cachix": "cachix", - "flake-compat": "flake-compat_2", - "nix": "nix_3", - "nixpkgs": [ - "nixpkgs" - ], - "pre-commit-hooks": "pre-commit-hooks_2" - }, - "locked": { - "lastModified": 1731081992, - "narHash": "sha256-1BlKyBDfkYQknlkqL6yAMKMG1NhSQ/6kq+oY1oWOQ+w=", - "owner": "cachix", - "repo": "devenv", - "rev": "ad1cfd1055e6bb8e0d6f3b7aa7bf00e5b374f0a4", - "type": "github" - }, - "original": { - "owner": "cachix", - "repo": "devenv", - "type": "github" - } - }, - "devenv_2": { - "inputs": { - "cachix": "cachix_2", - "flake-compat": [ - "devenv", - "cachix", - "flake-compat" - ], - "nix": "nix_2", + "flake-compat": "flake-compat", + "git-hooks": "git-hooks", + "nix": "nix", "nixpkgs": [ - "devenv", - "cachix", "nixpkgs" - ], - "pre-commit-hooks": [ - "devenv", - "cachix", - "git-hooks" - ] - }, - "locked": { - "lastModified": 1723156315, - "narHash": "sha256-0JrfahRMJ37Rf1i0iOOn+8Z4CLvbcGNwa2ChOAVrp/8=", - "owner": "cachix", - "repo": "devenv", - "rev": "ff5eb4f2accbcda963af67f1a1159e3f6c7f5f91", - "type": "github" - }, - "original": { - "owner": "cachix", - "repo": "devenv", - "type": "github" - } - }, - "devenv_3": { - "inputs": { - "flake-compat": [ - "devenv", - "cachix", - "devenv", - "cachix", - "flake-compat" - ], - "nix": "nix", - "nixpkgs": "nixpkgs", - "poetry2nix": "poetry2nix", - "pre-commit-hooks": [ - "devenv", - "cachix", - "devenv", - "cachix", - "pre-commit-hooks" ] }, "locked": { - "lastModified": 1708704632, - "narHash": "sha256-w+dOIW60FKMaHI1q5714CSibk99JfYxm0CzTinYWr+Q=", + "lastModified": 1731407985, + "narHash": "sha256-CnkW+Bigb4ocHtUXoRZ3PBlpGuRNFgHYK0IDk7SNyDg=", "owner": "cachix", "repo": "devenv", - "rev": "2ee4450b0f4b95a1b90f2eb5ffea98b90e48c196", + "rev": "9d3bf4d4c3fef89d2b6b29ebd64047a29ee932ea", "type": "github" }, "original": { "owner": "cachix", - "ref": "python-rewrite", "repo": "devenv", "type": "github" } @@ -167,11 +60,11 @@ "rust-analyzer-src": "rust-analyzer-src" }, "locked": { - "lastModified": 1731047492, - "narHash": "sha256-F4h8YtTzPWv0/1Z6fc8fMSqKpn7YhOjlgp66cr15tEo=", + "lastModified": 1731479620, + "narHash": "sha256-jBYFboMLYs0LcIfZq+kprR4vOjz6cfqaS8trwogoXQE=", "owner": "nix-community", "repo": "fenix", - "rev": "da6332e801fbb0418f80f20cefa947c5fe5c18c9", + "rev": "46c04695cd28be15ff88e3b8d2716818b034c084", "type": "github" }, "original": { @@ -181,22 +74,6 @@ } }, "flake-compat": { - "flake": false, - "locked": { - "lastModified": 1673956053, - "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=", - "owner": "edolstra", - "repo": "flake-compat", - "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9", - "type": "github" - }, - "original": { - "owner": "edolstra", - "repo": "flake-compat", - "type": "github" - } - }, - "flake-compat_2": { "flake": false, "locked": { "lastModified": 1696426674, @@ -234,36 +111,31 @@ "type": "github" } }, - "flake-utils": { + "git-hooks": { "inputs": { - "systems": "systems" - }, - "locked": { - "lastModified": 1689068808, - "narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=", - "owner": "numtide", - "repo": "flake-utils", - "rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4", - "type": "github" + "flake-compat": [ + "devenv" + ], + "gitignore": "gitignore", + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "nixpkgs-stable": [ + "devenv" + ] }, - "original": { - "owner": "numtide", - "repo": "flake-utils", - "type": "github" - } - }, - "flake-utils_2": { "locked": { - "lastModified": 1667395993, - "narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=", - "owner": "numtide", - "repo": "flake-utils", - "rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f", + "lastModified": 1730302582, + "narHash": "sha256-W1MIJpADXQCgosJZT8qBYLRuZls2KSiKdpnTVdKBuvU=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "af8a16fe5c264f5e9e18bcee2859b40a656876cf", "type": "github" }, "original": { - "owner": "numtide", - "repo": "flake-utils", + "owner": "cachix", + "repo": "git-hooks.nix", "type": "github" } }, @@ -271,7 +143,7 @@ "inputs": { "nixpkgs": [ "devenv", - "pre-commit-hooks", + "git-hooks", "nixpkgs" ] }, @@ -306,102 +178,22 @@ } }, "nix": { - "inputs": { - "flake-compat": "flake-compat", - "nixpkgs": [ - "devenv", - "cachix", - "devenv", - "cachix", - "devenv", - "nixpkgs" - ], - "nixpkgs-regression": "nixpkgs-regression" - }, - "locked": { - "lastModified": 1712911606, - "narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=", - "owner": "domenkozar", - "repo": "nix", - "rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12", - "type": "github" - }, - "original": { - "owner": "domenkozar", - "ref": "devenv-2.21", - "repo": "nix", - "type": "github" - } - }, - "nix-github-actions": { - "inputs": { - "nixpkgs": [ - "devenv", - "cachix", - "devenv", - "cachix", - "devenv", - "poetry2nix", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1688870561, - "narHash": "sha256-4UYkifnPEw1nAzqqPOTL2MvWtm3sNGw1UTYTalkTcGY=", - "owner": "nix-community", - "repo": "nix-github-actions", - "rev": "165b1650b753316aa7f1787f3005a8d2da0f5301", - "type": "github" - }, - "original": { - "owner": "nix-community", - "repo": "nix-github-actions", - "type": "github" - } - }, - "nix_2": { - "inputs": { - "flake-compat": [ - "devenv", - "cachix", - "devenv", - "flake-compat" - ], - "nixpkgs": [ - "devenv", - "cachix", - "devenv", - "nixpkgs" - ], - "nixpkgs-regression": "nixpkgs-regression_2" - }, - "locked": { - "lastModified": 1712911606, - "narHash": "sha256-BGvBhepCufsjcUkXnEEXhEVjwdJAwPglCC2+bInc794=", - "owner": "domenkozar", - "repo": "nix", - "rev": "b24a9318ea3f3600c1e24b4a00691ee912d4de12", - "type": "github" - }, - "original": { - "owner": "domenkozar", - "ref": "devenv-2.21", - "repo": "nix", - "type": "github" - } - }, - "nix_3": { "inputs": { "flake-compat": [ - "devenv", - "flake-compat" + "devenv" ], "flake-parts": "flake-parts", "libgit2": "libgit2", "nixpkgs": "nixpkgs_2", - "nixpkgs-23-11": "nixpkgs-23-11", - "nixpkgs-regression": "nixpkgs-regression_3", - "pre-commit-hooks": "pre-commit-hooks" + "nixpkgs-23-11": [ + "devenv" + ], + "nixpkgs-regression": [ + "devenv" + ], + "pre-commit-hooks": [ + "devenv" + ] }, "locked": { "lastModified": 1727438425, @@ -420,96 +212,16 @@ }, "nixpkgs": { "locked": { - "lastModified": 1692808169, - "narHash": "sha256-x9Opq06rIiwdwGeK2Ykj69dNc2IvUH1fY55Wm7atwrE=", + "lastModified": 1730531603, + "narHash": "sha256-Dqg6si5CqIzm87sp57j5nTaeBbWhHFaVyG7V6L8k3lY=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "9201b5ff357e781bf014d0330d18555695df7ba8", + "rev": "7ffd9ae656aec493492b44d0ddfb28e79a1ea25d", "type": "github" }, "original": { "owner": "NixOS", - "ref": "nixpkgs-unstable", - "repo": "nixpkgs", - "type": "github" - } - }, - "nixpkgs-23-11": { - "locked": { - "lastModified": 1717159533, - "narHash": "sha256-oamiKNfr2MS6yH64rUn99mIZjc45nGJlj9eGth/3Xuw=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "a62e6edd6d5e1fa0329b8653c801147986f8d446", - "type": "github" - }, - "original": { - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "a62e6edd6d5e1fa0329b8653c801147986f8d446", - "type": "github" - } - }, - "nixpkgs-regression": { - "locked": { - "lastModified": 1643052045, - "narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", - "type": "github" - }, - "original": { - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", - "type": "github" - } - }, - "nixpkgs-regression_2": { - "locked": { - "lastModified": 1643052045, - "narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", - "type": "github" - }, - "original": { - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", - "type": "github" - } - }, - "nixpkgs-regression_3": { - "locked": { - "lastModified": 1643052045, - "narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", - "type": "github" - }, - "original": { - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2", - "type": "github" - } - }, - "nixpkgs-stable": { - "locked": { - "lastModified": 1720386169, - "narHash": "sha256-NGKVY4PjzwAa4upkGtAMz1npHGoRzWotlSnVlqI40mo=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "194846768975b7ad2c4988bdb82572c00222c0d7", - "type": "github" - }, - "original": { - "owner": "NixOS", - "ref": "nixos-24.05", + "ref": "nixos-unstable", "repo": "nixpkgs", "type": "github" } @@ -532,11 +244,11 @@ }, "nixpkgs_3": { "locked": { - "lastModified": 1730785428, - "narHash": "sha256-Zwl8YgTVJTEum+L+0zVAWvXAGbWAuXHax3KzuejaDyo=", + "lastModified": 1731139594, + "narHash": "sha256-IigrKK3vYRpUu+HEjPL/phrfh7Ox881er1UEsZvw9Q4=", "owner": "nixos", "repo": "nixpkgs", - "rev": "4aa36568d413aca0ea84a1684d2d46f55dbabad7", + "rev": "76612b17c0ce71689921ca12d9ffdc9c23ce40b2", "type": "github" }, "original": { @@ -546,112 +258,22 @@ "type": "github" } }, - "poetry2nix": { - "inputs": { - "flake-utils": "flake-utils", - "nix-github-actions": "nix-github-actions", - "nixpkgs": [ - "devenv", - "cachix", - "devenv", - "cachix", - "devenv", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1692876271, - "narHash": "sha256-IXfZEkI0Mal5y1jr6IRWMqK8GW2/f28xJenZIPQqkY0=", - "owner": "nix-community", - "repo": "poetry2nix", - "rev": "d5006be9c2c2417dafb2e2e5034d83fabd207ee3", - "type": "github" - }, - "original": { - "owner": "nix-community", - "repo": "poetry2nix", - "type": "github" - } - }, - "pre-commit-hooks": { - "inputs": { - "flake-compat": [ - "devenv", - "nix" - ], - "flake-utils": "flake-utils_2", - "gitignore": [ - "devenv", - "nix" - ], - "nixpkgs": [ - "devenv", - "nix", - "nixpkgs" - ], - "nixpkgs-stable": [ - "devenv", - "nix", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1712897695, - "narHash": "sha256-nMirxrGteNAl9sWiOhoN5tIHyjBbVi5e2tgZUgZlK3Y=", - "owner": "cachix", - "repo": "pre-commit-hooks.nix", - "rev": "40e6053ecb65fcbf12863338a6dcefb3f55f1bf8", - "type": "github" - }, - "original": { - "owner": "cachix", - "repo": "pre-commit-hooks.nix", - "type": "github" - } - }, - "pre-commit-hooks_2": { - "inputs": { - "flake-compat": [ - "devenv", - "flake-compat" - ], - "gitignore": "gitignore", - "nixpkgs": [ - "devenv", - "nixpkgs" - ], - "nixpkgs-stable": "nixpkgs-stable" - }, - "locked": { - "lastModified": 1726745158, - "narHash": "sha256-D5AegvGoEjt4rkKedmxlSEmC+nNLMBPWFxvmYnVLhjk=", - "owner": "cachix", - "repo": "pre-commit-hooks.nix", - "rev": "4e743a6920eab45e8ba0fbe49dc459f1423a4b74", - "type": "github" - }, - "original": { - "owner": "cachix", - "repo": "pre-commit-hooks.nix", - "type": "github" - } - }, "root": { "inputs": { "devenv": "devenv", "fenix": "fenix", "nixpkgs": "nixpkgs_3", - "systems": "systems_2" + "systems": "systems" } }, "rust-analyzer-src": { "flake": false, "locked": { - "lastModified": 1730989300, - "narHash": "sha256-ZWSta9893f/uF5PoRFn/BSUAxF4dKW+TIbdA6rZoGBg=", + "lastModified": 1731342671, + "narHash": "sha256-36eYDHoPzjavnpmEpc2MXdzMk557S0YooGms07mDuKk=", "owner": "rust-lang", "repo": "rust-analyzer", - "rev": "1042a8c22c348491a4bade4f664430b03d6f5b5c", + "rev": "fc98e0657abf3ce07eed513e38274c89bbb2f8ad", "type": "github" }, "original": { @@ -675,21 +297,6 @@ "repo": "default", "type": "github" } - }, - "systems_2": { - "locked": { - "lastModified": 1681028828, - "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", - "owner": "nix-systems", - "repo": "default", - "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", - "type": "github" - }, - "original": { - "owner": "nix-systems", - "repo": "default", - "type": "github" - } } }, "root": "root", diff --git a/flake.nix b/flake.nix index 9772d5e..5973bd9 100644 --- a/flake.nix +++ b/flake.nix @@ -33,6 +33,7 @@ pkgs = nixpkgs.legacyPackages.${system}; in { + default = devenv.lib.mkShell { inherit inputs pkgs; modules = [ @@ -69,6 +70,7 @@ git bun taplo + bacon direnv sqlite deadnix diff --git a/src/lib.rs b/src/lib.rs index ce25fe3..462686f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,8 @@ +#![warn(clippy::all, clippy::pedantic, clippy::cargo)] use serde::{Deserialize, Serialize}; use serde_json::Value; use url::Url; -use worker::*; - -mod utils; -use utils::*; +use worker::{console_log, event, Context, Env, Request, Response, Result, RouteContext, Router}; #[derive(Deserialize, Serialize)] struct Record { @@ -13,28 +11,11 @@ struct Record { created_at: String, } -use std::fmt; - -impl fmt::Display for KvError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - KvError::Secret(msg) => write!(f, "Secret error: {}", msg), - KvError::Var(msg) => write!(f, "Var error: {}", msg), - } - } -} - -impl From for worker::Error { - fn from(error: KvError) -> Self { - worker::Error::from(error.to_string()) - } -} - const DEV_ROUTES: [&str; 2] = ["/list", "/env"]; #[event(fetch)] async fn fetch(request: Request, env: Env, _context: Context) -> Result { - let environment = get_var("ENVIRONMENT", &env).unwrap_or_default(); + let environment = env.var("ENVIRONMENT").unwrap().to_string(); if environment.trim().is_empty() { return Response::error("not allowed", 403); } @@ -48,11 +29,12 @@ async fn fetch(request: Request, env: Env, _context: Context) -> Result(None).await?.unwrap(); - - if let Value::Object(object) = result { - if let Some(Value::Number(id)) = object.get("id") { - return Response::ok(format!( - "https://{}/{}", - request.url().unwrap().host_str().unwrap(), - id - )); - } - } - Response::error("failed to insert new key", 500) + let result = query?.first::(None).await?; + + result + .unwrap() + .get("id") + .and_then(|o| o.as_str()) + .map_or_else( + || Response::error("failed to insert new key", 500), + |id| { + Response::ok(format!( + "https://{}/{}", + request.url().unwrap().host_str().unwrap(), + id + )) + }, + ) } // checks `GET /:key{[0-9]}` @@ -106,9 +92,11 @@ pub async fn handle_url_expand( return Response::error("invalid key: ".to_string() + key, 400); } - let d1 = context.env.d1("DB"); - let statement = d1?.prepare("SELECT url FROM urls WHERE id = ?"); - let query = statement.bind(&[key.into()]); + let query = context + .env + .d1("DB")? + .prepare("SELECT url FROM urls WHERE id = ?") + .bind(&[key.into()]); let result: Option = query?.first::(None).await?; match result { @@ -130,8 +118,8 @@ pub async fn dev_handle_list_urls( let d1 = context.env.d1("DB")?; let statement = d1.prepare("SELECT * FROM urls"); // let query = statement.bind(&[])?; - let result = statement.all().await?; + // let result = statement.all().await?; - let records: Vec = result.results()?; + let records: Vec = statement.all().await?.results()?; Response::from_json(&records) } diff --git a/src/utils.rs b/src/utils.rs deleted file mode 100644 index 85e1fb5..0000000 --- a/src/utils.rs +++ /dev/null @@ -1,21 +0,0 @@ -use std::result::Result; - -use worker::*; - -#[derive(Debug, Clone, PartialEq)] -pub enum KvError { - Var(String), - Secret(String), -} - -pub fn get_secret(name: &str, env: &Env) -> Result { - env.secret(name) - .map(|value| value.to_string()) - .map_err(|error| KvError::Secret(error.to_string())) -} - -pub fn get_var(name: &str, env: &Env) -> Result { - env.var(name) - .map(|value| value.to_string()) - .map_err(|error| KvError::Var(error.to_string())) -} diff --git a/tasks.nix b/tasks.nix index 6f7e4f8..567b03d 100644 --- a/tasks.nix +++ b/tasks.nix @@ -10,7 +10,7 @@ ''; lint.exec = '' taplo lint *.toml - cargo clippy --all-targets --all-features + cargo clippy --all-targets --all-features -- -A clippy::pedantic sqlfluff lint --dialect sqlite ./schema.sql deadnix --no-lambda-pattern-names && statix check . ''; From efd4d3fb988176c52752210e5c51d810d75b41ed Mon Sep 17 00:00:00 2001 From: o-az Date: Wed, 13 Nov 2024 06:04:44 -0800 Subject: [PATCH 3/5] chore: no pedantic default --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 462686f..7abbafc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -#![warn(clippy::all, clippy::pedantic, clippy::cargo)] +#![warn(clippy::all)] use serde::{Deserialize, Serialize}; use serde_json::Value; use url::Url; From 43f36b06576dd96a5f9beabe44b39fad1fbbf0d8 Mon Sep 17 00:00:00 2001 From: o-az Date: Wed, 13 Nov 2024 06:35:05 -0800 Subject: [PATCH 4/5] fix: create route --- src/lib.rs | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 7abbafc..6c54812 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -62,22 +62,18 @@ pub async fn handle_create( let query_statement = d1.prepare("SELECT id FROM urls ORDER BY id DESC LIMIT 1"); let query = query_statement.bind(&[]); - let result = query?.first::(None).await?; - - result - .unwrap() - .get("id") - .and_then(|o| o.as_str()) - .map_or_else( - || Response::error("failed to insert new key", 500), - |id| { - Response::ok(format!( - "https://{}/{}", - request.url().unwrap().host_str().unwrap(), - id - )) - }, - ) + let result = query?.first::(None).await?.unwrap(); + + if let Value::Object(object) = result { + if let Some(Value::Number(id)) = object.get("id") { + return Response::ok(format!( + "https://{}/{}", + request.url().unwrap().host_str().unwrap(), + id + )); + } + } + Response::error("failed to insert new key", 500) } // checks `GET /:key{[0-9]}` From 003b6ac9b0e637ddac2480a8c0ddecf794258372 Mon Sep 17 00:00:00 2001 From: o-az Date: Wed, 13 Nov 2024 06:49:34 -0800 Subject: [PATCH 5/5] fix: wrangler remote --- flake.nix | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/flake.nix b/flake.nix index 5973bd9..3f64245 100644 --- a/flake.nix +++ b/flake.nix @@ -38,6 +38,11 @@ inherit inputs pkgs; modules = [ { + enterShell = '' + # temporary wrangler fix: https://github.com/cloudflare/workers-sdk/issues/3264#issuecomment-1642939487 + export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt + ''; + # https://devenv.sh/reference/options/ scripts = import ./tasks.nix;