Endpoint using rocket, making a query in table users
#[post("/", data="<user>")]
pub async fn create_user(user: Json<User>, db: &State<Database>) -> Custom<Value> {
println!("Creating a new user");
let response = json!(
{
"status": "success",
"message": "User created successfully"
}
);
let db_res = db.query(format!("INSERT INTO users (name, email, password) VALUES ('{}', '{}', '{}')", user.name, user.email, user.password)).await;
println!("{:?}", db_res);
user_service::create_user();
status::Custom(Status::Created, response)
}
db_res
has the value:
Ok(Response { client: Surreal { router: OnceLock(Router { sender: Sender, last_id: 3, features: {LiveQueries} }), engine: PhantomData<surrealdb::api::engine::any::Any> }, results: {0: (Stats { execution_time: Some(233.411µs) }, Ok(Array(Array([Object(Object({"email": Strand(Strand("grizzy@email.com")), "id": Thing(Thing { tb: "users", id: String("j8g5v34qpq7mvs0bqdnf") }), "name": Strand(Strand("Grizzy")), "password": Strand(Strand("123"))}))]))))}, live_queries: {} })
How to extract only the user data from response and return a JSON on endpoint response?, like:
let user = // user data from db_res
let new_user = json!({
id: user.id,
name: user.name,
email: user.email,
})
This simulates the input you mentioned plus wraps it in Rocket's Json wrapper so I think it should do the trick. The .take() method will always work if you have a matching type to deserialize it into.
#[derive(Serialize, Deserialize, Debug)]
struct Users {
email: String,
name: String,
password: String,
}
let res: Vec<Users> = db
.query(
"create users SET
email = 'grizzy@email.com',
name = 'Grizzy',
password = '123';",
)
.await?.take(0)?;
Json(res)