The surreal-id
crate offers a standardized way to create and validate IDs in your application for usage with SurrealDB. By defining the NewId
trait, the crate streamlines the ID creation process, handling errors like malformed or empty IDs, and ensures consistency with associated table names. This also enables developers to serialize and deserialize custom ID types from SurrealDB whilst still retrieving the ID field for usage in your application, making it using custom ID types and logic with SurrealDB seamless.
```rs use serde::{Deserialize, Serialize}; use surreal_id::NewId; use surrealdb::{opt::RecordId, sql::Id};
pub const USERS_TABLE: &str = "users";
pub struct UserId(RecordId);
impl NewId for UserId { const TABLE: &'static str = USERS_TABLE;
fn from_inner_id<T: Into<Id>>(inner_id: T) -> Self {
UserId(RecordId {
tb: Self::TABLE.to_string(),
id: inner_id.into(),
})
}
} ```
NOTE: For most use cases, most of the above code is boilerplate that could be eliminated with a procerdural macro, where the only thing specified is the table name.
Now you can instantiate the UserId
type using new
, and use it in your struct with SurrealDB like so:
```rs
pub struct User { id: UserId, name: String, }
let usertobecreated = User { id: UserId::new("fa77edc3-56ed-4208-9e0b-c0b1c32e2d34").unwrap(), name: "John Doe".tostring(), };
let db = Surreal::new::
let createresult = db.create(USERSTABLE).content(&usertobecreated).await; let retrieveduser: User = create_result.unwrap().remove(0);
asserteq!(usertobecreated, retrieved_user) ```
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.