...

/

Read and Search Resources

Read and Search Resources

Learn the code needed for reading and searching products.

We'll cover the following...

Reading

The code to obtain data from one resource can be very straightforward if you are used to ORMs.

Press + to interact
use diesel::sqlite::SqliteConnection;
use diesel::result::Error;
use diesel::{QueryDsl, RunQueryDsl};
use ::shoe_store::models::Product;
fn show_product(id: i32, conn: &SqliteConnection) -> Result<Product, Error> {
use ::shoe_store::schema::products::dsl::products;
products
.find(id)
.first(conn)
}

We use first as a translation for LIMIT 1 SQL clause to find the product with the required id. Now, we can create a test.

Press + to interact
use diesel::result::Error;
use diesel::Connection;
use ::shoe_store::establish_connection_test;
use ::shoe_store::models::{Product, NewCompleteProduct, NewProduct, NewVariantValue, NewVariant};
#[test]
fn show_product_test() {
let connection = establish_connection_test();
connection.test_transaction::<_, Error, _>(|| {
let product_id =
create_product(NewCompleteProduct {
product: NewProduct {
name: "boots".to_string(),
cost: 13.23,
active: true
},
variants: vec![
NewVariantValue {
variant: NewVariant {
name: "size".to_string()
},
values: vec![
Some(12.to_string()),
Some(14.to_string()),
Some(16.to_string()),
Some(18.to_string())
]
}
]
}, &connection).unwrap();
assert_eq!(
serde_json::to_string(&show_product(product_id, &connection).unwrap()).unwrap(),
serde_json::to_string(
&Product {
id: 1,
name: "boots".to_string(),
cost: 13.23,
active: true
}
).unwrap()
);
Ok(())
});
}

In the previous code, we use ...