From 3ac8de13a4de29e5ed668d69a1209dddaabc9f30 Mon Sep 17 00:00:00 2001 From: Sarmad Gulzar Date: Tue, 3 Aug 2021 05:22:06 +0500 Subject: [PATCH] Added Base struct and get method (#2) --- Cargo.toml | 4 +++- README.md | 37 ++++++++++++++++++++++++++++++++++++- src/lib.rs | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0fecdac..fc6c7ba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "deta" -version = "0.1.0" +version = "0.2.0" edition = "2018" license-file = "LICENSE" description = "Deta SDK for Rust" @@ -12,3 +12,5 @@ readme = "README.md" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +reqwest = { version = "0.11.4", features = ["blocking", "json"] } +serde = { version = "1.0.127", features = ["derive"] } diff --git a/README.md b/README.md index 7262caa..2d0e72a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,38 @@ -# rust-deta +# data-rust Deta SDK for Rust + +Example: + +```rust +use base::Base; +use serde::Deserialize; + +#[derive(Debug, Deserialize)] +struct User { + key: String, + name: String, + age: i32, +} + +fn main() { + let base = Base::new( + String::from("DB_NAME"), + String::from("DB_PROJECT_KEY"), + String::from("DB_PROJECT_ID"), + ); + let user: User = base + .get(String::from("krvb876h")) + .expect("There was an error!") + .json() + .expect("There was an error!"); + + println!("{:?}", user); +} +``` + +This will print the following to the console: + +```raw +User { key: "krvb876h", name: "Sarmad", age: 25 } +``` diff --git a/src/lib.rs b/src/lib.rs index 31e1bb2..be88a5a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,39 @@ +pub mod base { + use reqwest::blocking::Client; + use reqwest::blocking::Response; + use reqwest::header::HeaderMap; + use reqwest::Method; + pub struct Base { + name: String, + project_key: String, + project_id: String, + host: String, + } + impl Base { + pub fn new(name: String, project_key: String, project_id: String) -> Self { + Base { + name: name, + project_key: project_key, + project_id: project_id, + host: String::from("https://database.deta.sh"), + } + } + pub fn get(&self, key: String) -> reqwest::Result { + self.request( + format!("/v1/{}/{}/items/{}", self.project_id, self.name, key), + Method::GET, + ) + } + fn request(&self, path: String, method: Method) -> reqwest::Result { + let client = Client::new(); + let url = format!("{}{}", self.host, path); + let mut headers = HeaderMap::new(); + headers.insert("X-Api-Key", self.project_key.parse().unwrap()); + let res = client.request(method, url).headers(headers).send(); + res + } + } +} #[cfg(test)] mod tests { #[test]