1
0
mirror of https://github.com/actix/examples synced 2025-06-26 17:17:42 +02:00

restructure folders

This commit is contained in:
Rob Ede
2022-02-18 02:01:48 +00:00
parent 4d8573c3fe
commit cc3d356209
201 changed files with 52 additions and 49 deletions

1
databases/diesel/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
test.db

View File

@ -0,0 +1,15 @@
[package]
name = "diesel-example"
version = "1.0.0"
edition = "2021"
[dependencies]
actix-web = "4.0.0-beta.21"
diesel = { version = "1.4.8", features = ["sqlite", "r2d2"] }
dotenv = "0.15"
env_logger = "0.9.0"
failure = "0.1.8"
futures = "0.3.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
uuid = { version = "0.8", features = ["serde", "v4"] }

109
databases/diesel/README.md Normal file
View File

@ -0,0 +1,109 @@
# diesel
Basic integration of [Diesel](https://diesel.rs/) using SQLite for Actix Web.
## Usage
### Install SQLite
```sh
# on OpenSUSE
sudo zypper install sqlite3-devel libsqlite3-0 sqlite3
# on Ubuntu
sudo apt-get install libsqlite3-dev sqlite3
# on Fedora
sudo dnf install libsqlite3x-devel sqlite3x
# on macOS (using homebrew)
brew install sqlite3
```
### Initialize SQLite Database
```sh
cd examples/diesel
cargo install diesel_cli --no-default-features --features sqlite
echo "DATABASE_URL=test.db" > .env
diesel migration run
```
There will now be a database file at `./test.db`.
### Running Server
```sh
cd examples/diesel
cargo run (or ``cargo watch -x run``)
# Started http server: 127.0.0.1:8080
```
### Available Routes
#### `POST /user`
Inserts a new user into the SQLite DB.
Provide a JSON payload with a name. Eg:
```json
{ "name": "bill" }
```
On success, a response like the following is returned:
```json
{
"id": "9e46baba-a001-4bb3-b4cf-4b3e5bab5e97",
"name": "bill"
}
```
<details>
<summary>Client Examples</summary>
Using [HTTPie](https://httpie.org/):
```sh
http POST localhost:8080/user name=bill
```
Using cURL:
```sh
curl -S -X POST --header "Content-Type: application/json" --data '{"name":"bill"}' http://localhost:8080/user
```
</details>
#### `GET /user/{user_uid}`
Gets a user from the DB using its UID (returned from the insert request or taken from the DB directly). Returns a 404 when no user exists with that UID.
<details>
<summary>Client Examples</summary>
Using [HTTPie](https://httpie.org/):
```sh
http localhost:8080/user/9e46baba-a001-4bb3-b4cf-4b3e5bab5e97
```
Using cURL:
```sh
curl -S http://localhost:8080/user/9e46baba-a001-4bb3-b4cf-4b3e5bab5e97
```
</details>
### Explore The SQLite DB
```sh
sqlite3 test.db
```
```
sqlite> .tables
sqlite> SELECT * FROM users;
```
## Using Other Databases
You can find a complete example of Diesel + PostgreSQL at: [https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix](https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix)

View File

@ -0,0 +1 @@
DROP TABLE users

View File

@ -0,0 +1,4 @@
CREATE TABLE users (
id VARCHAR NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL
)

View File

@ -0,0 +1,42 @@
use diesel::prelude::*;
use uuid::Uuid;
use crate::models;
type DbError = Box<dyn std::error::Error + Send + Sync>;
/// Run query using Diesel to find user by uid and return it.
pub fn find_user_by_uid(
uid: Uuid,
conn: &SqliteConnection,
) -> Result<Option<models::User>, DbError> {
use crate::schema::users::dsl::*;
let user = users
.filter(id.eq(uid.to_string()))
.first::<models::User>(conn)
.optional()?;
Ok(user)
}
/// Run query using Diesel to insert a new database row and return the result.
pub fn insert_new_user(
// prevent collision with `name` column imported inside the function
nm: &str,
conn: &SqliteConnection,
) -> Result<models::User, DbError> {
// It is common when using Diesel with Actix Web to import schema-related
// modules inside a function's scope (rather than the normal module's scope)
// to prevent import collisions and namespace pollution.
use crate::schema::users::dsl::*;
let new_user = models::User {
id: Uuid::new_v4().to_string(),
name: nm.to_owned(),
};
diesel::insert_into(users).values(&new_user).execute(conn)?;
Ok(new_user)
}

View File

@ -0,0 +1,146 @@
//! Actix Web Diesel integration example
//!
//! Diesel does not support tokio, so we have to run it in separate threads using the web::block
//! function which offloads blocking code (like Diesel's) in order to not block the server's thread.
#[macro_use]
extern crate diesel;
use actix_web::{get, middleware, post, web, App, Error, HttpResponse, HttpServer};
use diesel::prelude::*;
use diesel::r2d2::{self, ConnectionManager};
use uuid::Uuid;
mod actions;
mod models;
mod schema;
type DbPool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
/// Finds user by UID.
#[get("/user/{user_id}")]
async fn get_user(
pool: web::Data<DbPool>,
user_uid: web::Path<Uuid>,
) -> Result<HttpResponse, Error> {
let user_uid = user_uid.into_inner();
// use web::block to offload blocking Diesel code without blocking server thread
let user = web::block(move || {
let conn = pool.get()?;
actions::find_user_by_uid(user_uid, &conn)
})
.await?
.map_err(actix_web::error::ErrorInternalServerError)?;
if let Some(user) = user {
Ok(HttpResponse::Ok().json(user))
} else {
let res = HttpResponse::NotFound()
.body(format!("No user found with uid: {}", user_uid));
Ok(res)
}
}
/// Inserts new user with name defined in form.
#[post("/user")]
async fn add_user(
pool: web::Data<DbPool>,
form: web::Json<models::NewUser>,
) -> Result<HttpResponse, Error> {
// use web::block to offload blocking Diesel code without blocking server thread
let user = web::block(move || {
let conn = pool.get()?;
actions::insert_new_user(&form.name, &conn)
})
.await?
.map_err(actix_web::error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(user))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
dotenv::dotenv().ok();
// set up database connection pool
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
let manager = ConnectionManager::<SqliteConnection>::new(connspec);
let pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
let bind = ("127.0.0.1", 8080);
println!("Starting server at: {}", &bind);
// Start HTTP server
HttpServer::new(move || {
App::new()
// set up DB pool to be used with web::Data<Pool> extractor
.app_data(web::Data::new(pool.clone()))
.wrap(middleware::Logger::default())
.service(get_user)
.service(add_user)
})
.bind(&bind)?
.run()
.await
}
#[cfg(test)]
mod tests {
use super::*;
use actix_web::test;
#[actix_web::test]
async fn user_routes() {
std::env::set_var("RUST_LOG", "actix_web=debug");
env_logger::init();
dotenv::dotenv().ok();
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
let manager = ConnectionManager::<SqliteConnection>::new(connspec);
let pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
let mut app = test::init_service(
App::new()
.app_data(web::Data::new(pool.clone()))
.wrap(middleware::Logger::default())
.service(get_user)
.service(add_user),
)
.await;
// Insert a user
let req = test::TestRequest::post()
.uri("/user")
.set_json(&models::NewUser {
name: "Test user".to_owned(),
})
.to_request();
let resp: models::User = test::call_and_read_body_json(&mut app, req).await;
assert_eq!(resp.name, "Test user");
// Get a user
let req = test::TestRequest::get()
.uri(&format!("/user/{}", resp.id))
.to_request();
let resp: models::User = test::call_and_read_body_json(&mut app, req).await;
assert_eq!(resp.name, "Test user");
// Delete new user from table
use crate::schema::users::dsl::*;
diesel::delete(users.filter(id.eq(resp.id)))
.execute(&pool.get().expect("couldn't get db connection from pool"))
.expect("couldn't delete test user from table");
}
}

View File

@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
use crate::schema::users;
#[derive(Debug, Clone, Serialize, Deserialize, Queryable, Insertable)]
pub struct User {
pub id: String,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NewUser {
pub name: String,
}

View File

@ -0,0 +1,6 @@
table! {
users (id) {
id -> Text,
name -> Text,
}
}