surrealpatch/sdk/examples/axum/src/person.rs

51 lines
1.2 KiB
Rust
Raw Normal View History

2023-03-20 15:20:57 +00:00
use crate::error::Error;
use axum::extract::Path;
use axum::extract::State;
use axum::Json;
use serde::Deserialize;
use serde::Serialize;
2024-02-19 15:11:58 +00:00
use surrealdb::engine::any::Any;
2023-03-20 15:20:57 +00:00
use surrealdb::Surreal;
const PERSON: &str = "person";
2024-02-19 15:11:58 +00:00
type Db = State<Surreal<Any>>;
2023-03-20 15:20:57 +00:00
#[derive(Serialize, Deserialize)]
pub struct Person {
name: String,
}
pub async fn create(
db: Db,
id: Path<String>,
Json(person): Json<Person>,
) -> Result<Json<Option<Person>>, Error> {
2023-03-20 15:20:57 +00:00
let person = db.create((PERSON, &*id)).content(person).await?;
Ok(Json(person))
}
pub async fn read(db: Db, id: Path<String>) -> Result<Json<Option<Person>>, Error> {
let person = db.select((PERSON, &*id)).await?;
Ok(Json(person))
}
pub async fn update(
db: Db,
id: Path<String>,
Json(person): Json<Person>,
) -> Result<Json<Option<Person>>, Error> {
2023-03-20 15:20:57 +00:00
let person = db.update((PERSON, &*id)).content(person).await?;
Ok(Json(person))
}
pub async fn delete(db: Db, id: Path<String>) -> Result<Json<Option<Person>>, Error> {
let person = db.delete((PERSON, &*id)).await?;
Ok(Json(person))
2023-03-20 15:20:57 +00:00
}
pub async fn list(db: Db) -> Result<Json<Vec<Person>>, Error> {
let people = db.select(PERSON).await?;
Ok(Json(people))
}