Refactor the Axum example (#3542)

This commit is contained in:
Pratim 2024-02-19 20:41:58 +05:30 committed by GitHub
parent 1e5bd504b2
commit c83928be13
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 33 additions and 17 deletions

View file

@ -7,6 +7,6 @@ publish = false
[dependencies]
axum = "0.7.2"
serde = { version = "1.0.193", features = ["derive"] }
surrealdb = { path = "../.." }
surrealdb = { path = "../.." ,features = ["kv-mem"]}
thiserror = "1.0.50"
tokio = { version = "1.34.0", features = ["macros", "rt-multi-thread"] }

View file

@ -0,0 +1,24 @@
pub mod error;
pub mod person;
use axum::{
routing::{delete, get, post, put},
Router,
};
use surrealdb::engine::any::Any;
use surrealdb::Surreal;
pub fn create_router(db: Surreal<Any>) -> Router {
Router::new()
//curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe"}' http://localhost:8080/person/1
.route("/person/:id", post(person::create))
//curl -X GET http://localhost:8080/person/1
.route("/person/:id", get(person::read))
//curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane Doe"}' http://localhost:8080/person/1
.route("/person/:id", put(person::update))
//curl -X DELETE http://localhost:8080/person/1
.route("/person/:id", delete(person::delete))
//curl -X GET http://localhost:8080/people
.route("/people", get(person::list))
.with_state(db)
}

View file

@ -1,16 +1,15 @@
mod error;
mod person;
use axum::routing::{delete, get, post, put};
use axum::Router;
use surrealdb::engine::remote::ws::Ws;
use axum_example::create_router;
use std::env;
use surrealdb::engine::any;
use surrealdb::opt::auth::Root;
use surrealdb::Surreal;
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let db = Surreal::new::<Ws>("localhost:8000").await?;
let endpoint = env::var("SURREALDB_ENDPOINT").unwrap_or_else(|_| "memory".to_owned());
let db = any::connect(endpoint).await?;
db.signin(Root {
username: "root",
@ -20,15 +19,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
db.use_ns("namespace").use_db("database").await?;
let router = Router::new()
.route("/person/:id", post(person::create))
.route("/person/:id", get(person::read))
.route("/person/:id", put(person::update))
.route("/person/:id", delete(person::delete))
.route("/people", get(person::list))
.with_state(db);
let listener = TcpListener::bind("localhost:8080").await?;
let router = create_router(db);
axum::serve(listener, router).await?;

View file

@ -4,12 +4,12 @@ use axum::extract::State;
use axum::Json;
use serde::Deserialize;
use serde::Serialize;
use surrealdb::engine::remote::ws::Client;
use surrealdb::engine::any::Any;
use surrealdb::Surreal;
const PERSON: &str = "person";
type Db = State<Surreal<Client>>;
type Db = State<Surreal<Any>>;
#[derive(Serialize, Deserialize)]
pub struct Person {