Skip to content

Commit

Permalink
Change Post to Product
Browse files Browse the repository at this point in the history
Adapt `README.md`
Change the migrations scripts
Change all the references (functions and structs)
  • Loading branch information
n-pochet committed Feb 9, 2018
1 parent 4d2d646 commit c8135b9
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 62 deletions.
14 changes: 7 additions & 7 deletions examples/diesel/README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Basic Diesel
# Diesel Example

An example of the Gotham Diesel Middelware.

## Running

From the `examples/basic_diesel` directory:
From the `examples/diesel` directory:

```
Terminal 1:
Expand Down Expand Up @@ -33,7 +33,7 @@ $ curl -v http://127.0.0.1:7878
* Connection #0 to host localhost left intact
[]%
$ curl -v -H "Content-Type: application/json" -X POST -d '{"title":"test","body":"body","published":true}' 'http://localhost:7878'
$ curl -v -H "Content-Type: application/json" -X POST -d '{"title":"test","price":1.0,"link":"http://localhost"}' 'http://localhost:7878'
Note: Unnecessary use of -X or --request, POST is already inferred.
* Rebuilt URL to: http://localhost:7878/
* Trying 127.0.0.1...
Expand Down Expand Up @@ -66,16 +66,16 @@ $ curl -v localhost:7878
* Connected to localhost (127.0.0.1) port 7878 (#0)
> GET / HTTP/1.1
> Host: localhost:7878
> User-Agent: curl/7.57.0
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 200 OK
< X-Runtime-Microseconds: 261
< X-Runtime-Microseconds: 427
< Transfer-Encoding: chunked
< Date: Fri, 02 Feb 2018 21:42:40 GMT
< Date: Tue, 06 Feb 2018 18:54:12 GMT
<
* Connection #0 to host localhost left intact
[{"id":1,"title":"test","body":"body","published":true}]
[{"id":1,"title":"test","price":1.0,"link":"http://localhost"}]%
```

## License
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
DROP TABLE posts
DROP TABLE products
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
CREATE TABLE posts (
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
title VARCHAR NOT NULL,
body TEXT NOT NULL,
published BOOLEAN NOT NULL DEFAULT 'f'
price REAL NOT NULL,
link VARCHAR NOT NULL
)
40 changes: 20 additions & 20 deletions examples/diesel/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! This module holds the functions to get and create posts from the DB.
//! This module holds the functions to get and create products from the DB.

pub mod schema;
pub mod models;
Expand All @@ -15,42 +15,42 @@ extern crate serde;
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;

use self::models::{Post, NewPost};
use self::schema::posts::dsl::{posts, published};
use self::models::{Product, NewProduct};
use self::schema::products::dsl::products;

embed_migrations!();

/// Get the published posts in the DB. Limitted to 5 posts.
pub fn get_posts(conn: &SqliteConnection) -> Vec<Post> {
// Run the migrations to be sure that the `posts` table is present
/// Get the published products in the DB. Limitted to 5 products.
pub fn get_products(conn: &SqliteConnection) -> Vec<Product> {
// Run the migrations to be sure that the `products` table is present
let _result = embedded_migrations::run(conn);

posts
.filter(published.eq(true))
products
.limit(5)
.load::<Post>(conn)
.load::<Product>(conn)
.unwrap()
}

/// Create a new post in the DB.
pub fn create_post<'a>(
/// Create a new product in the DB.
pub fn create_product<'a>(
conn: &SqliteConnection,
title: &'a str,
body: &'a str,
price: f32,
link: String
) -> QueryResult<usize> {
use schema::posts;
// Run the migrations to be sure that the `posts` table is present
use schema::products;
// Run the migrations to be sure that the `products` table is present
let _result = embedded_migrations::run(conn);

let new_post = NewPost {
let new_product = NewProduct{
title: title,
body: body,
published: true,
price: price,
link: link,
};

// Insert the `NewPost` in the DB
diesel::insert_into(posts::table)
.values(&new_post)
// Insert the `NewProduct` in the DB
diesel::insert_into(products::table)
.values(&new_product)
.execute(conn)
}

36 changes: 18 additions & 18 deletions examples/diesel/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ use r2d2_diesel::ConnectionManager;
use r2d2::{Pool, PooledConnection};
use futures::{future, Future, Stream};
use std::str;
use basic_diesel::models::NewPost;
use basic_diesel::models::NewProduct;


// The URL of the database.
static DATABASE_URL: &'static str = "posts.db";
static DATABASE_URL: &'static str = "products.db";


/// Creates the `DieselMiddleware` from an `url` that is passed to the function
Expand All @@ -39,36 +39,36 @@ fn create_middleware(url: &str) -> DieselMiddleware<SqliteConnection> {
DieselMiddleware::with_pool(pool)
}

/// Handler function. Responsible of getting and displaying the posts from the DB
fn get_posts_handler(state: State) -> (State, Response) {
/// Handler function. Responsible of getting and displaying the products from the DB
fn get_products_handler(state: State) -> (State, Response) {
let conn: PooledConnection<ConnectionManager<SqliteConnection>> =
gotham_middleware_diesel::state_data::connection(&state);
let posts = basic_diesel::get_posts(&conn);
let products = basic_diesel::get_products(&conn);

(
state,
Response::new().with_status(StatusCode::Ok).with_body(
format!(
"{}",
serde_json::to_string(&posts).unwrap()
serde_json::to_string(&products).unwrap()
),
),
)
}

/// Handle function. Manages the `NewPost` to insert to the DB
fn post_post_handler(mut state: State) -> Box<HandlerFuture> {
/// Handle function. Manages the `NewProduct` to insert to the DB
fn post_product_handler(mut state: State) -> Box<HandlerFuture> {
let f = hyper::Body::take_from(&mut state).concat2().then(
move |full_body| match full_body {
Ok(valid_body) => {
let post: NewPost = match serde_json::from_slice(&valid_body) {
let product : NewProduct = match serde_json::from_slice(&valid_body) {
Ok(p) => p,
Err(e) => return future::err((state, e.into_handler_error())),
};
let conn: PooledConnection<ConnectionManager<SqliteConnection>> =
gotham_middleware_diesel::state_data::connection(&state);
let mut res: Response;
match basic_diesel::create_post(&conn, post.title, post.body) {
match basic_diesel::create_product(&conn, product.title, product.price, product.link){
Ok(_) => {
res = create_response(
&state,
Expand All @@ -94,8 +94,8 @@ fn post_post_handler(mut state: State) -> Box<HandlerFuture> {
///
/// / --> GET, POST
///
/// It returns the content of the SQLite DB file located in `.posts.db`
/// This DB consists of `Post` entries.
/// It returns the content of the SQLite DB file located in `products.db`
/// This DB consists of `Products` entries.
fn router(middleware: DieselMiddleware<SqliteConnection>) -> Router {
// Create a new pipeline set
let editable_pipeline_set = new_pipeline_set();
Expand All @@ -109,8 +109,8 @@ fn router(middleware: DieselMiddleware<SqliteConnection>) -> Router {

// Build the router
build_router(default_pipeline_chain, pipeline_set, |route| {
route.get("/").to(get_posts_handler);
route.post("/").to(post_post_handler);
route.get("/").to(get_products_handler);
route.post("/").to(post_product_handler);
})
}

Expand All @@ -135,7 +135,7 @@ mod tests {


#[test]
fn get_empty_posts() {
fn get_empty_products() {
let middleware = create_middleware("empty.db");
let test_server = TestServer::new(router(middleware)).unwrap();
let response = test_server
Expand All @@ -153,10 +153,10 @@ mod tests {
}

#[test]
fn create_post() {
let middleware = create_middleware("test_post.db");
fn create_product() {
let middleware = create_middleware("test_products.db");
let test_server = TestServer::new(router(middleware)).unwrap();
let body = "{\"title\":\"test\",\"body\":\"test post\",\"published\":true}";
let body = "{\"title\":\"test\",\"price\":1.0,\"link\":\"http://localhost\"}";
let response = test_server
.client()
.post("http://localhost", body, mime::APPLICATION_JSON)
Expand Down
20 changes: 10 additions & 10 deletions examples/diesel/src/models.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
//! Holds the two possible structs that are `Queryable` and
//! `Insertable` in the DB

use super::schema::posts;
use super::schema::products;

/// Represents a post in the DB.
/// Represents a product in the DB.
/// It is `Queryable`
#[derive(Queryable, Serialize, Debug)]
pub struct Post {
pub struct Product {
pub id: Option<i32>,
pub title: String,
pub body: String,
pub published: bool,
pub price: f32,
pub link: String,
}

/// Represents a new post to insert in the DB.
/// Represents a new product to insert in the DB.
#[derive(Insertable, Deserialize)]
#[table_name = "posts"]
pub struct NewPost<'a> {
#[table_name = "products"]
pub struct NewProduct<'a> {
pub title: &'a str,
pub body: &'a str,
pub published: bool,
pub price: f32,
pub link: String,
}
6 changes: 3 additions & 3 deletions examples/diesel/src/schema.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
table! {
posts (id) {
products (id) {
id -> Nullable<Integer>,
title -> Text,
body -> Text,
published -> Bool,
price -> Float,
link -> Text,
}
}

0 comments on commit c8135b9

Please sign in to comment.