Skip to content

Commit

Permalink
Merge pull request docker#35 from jdrouet/react-rust
Browse files Browse the repository at this point in the history
create a react-rust-postgres example
  • Loading branch information
glours authored Mar 27, 2020
2 parents 60d2d2a + 7d518e1 commit 11c633b
Show file tree
Hide file tree
Showing 39 changed files with 15,883 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ docker-compose down
application with a Spring backend and a MySQL database
- [`React / Express / MySQL`](react-express-mysql) -- sample React
application with a NodeJS backend and a MySQL database
- [`React / Rust / PostgreSQL`](react-rust-postgres) -- sample React
application with a Rust backend and a Postgres database
- [`Spring / PostgreSQL`](spring-postgres) -- sample Java application
with Spring framework and a Postgres database

Expand All @@ -67,7 +69,7 @@ docker-compose down
- [`VueJS`](vuejs)
- [`Flask`](flask)

*Basic setups for different plaforms (not production ready - useful for personal use)*
*Basic setups for different plaforms (not production ready - useful for personal use)*
- [`Gitea / PostgreSQL`](gitea-postgres)
- [`Nextcloud / PostgreSQL`](nextcloud-postgres)
- [`Nextcloud / Redis / MariaDB`](nextcloud-redis-mariadb)
Expand Down
2 changes: 2 additions & 0 deletions react-rust-postgres/backend/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
target
Cargo.lock
2 changes: 2 additions & 0 deletions react-rust-postgres/backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
target
Cargo.lock
23 changes: 23 additions & 0 deletions react-rust-postgres/backend/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[package]
name = "react-rust-postgres"
version = "0.1.0"
authors = ["Jérémie Drouet <jeremie.drouet@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
diesel_migrations = "1.4.0"
rocket = "0.4.4"
serde = "1.0"
serde_json = "1.0"
serde_derive = "1.0"

[dependencies.diesel]
version = "1.0.0"
features = ["postgres"]

[dependencies.rocket_contrib]
version = "0.4.4"
default-features = false
features = ["json", "diesel_postgres_pool"]
35 changes: 35 additions & 0 deletions react-rust-postgres/backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
FROM jdrouet/rust-nightly:buster-slim AS base

RUN apt-get update \
&& apt-get install -y libpq-dev \
&& rm -rf /var/lib/apt/lists/*

ENV USER=root
ENV ROCKET_ADDRESS=0.0.0.0
ENV ROCKET_ENV=development

WORKDIR /code
RUN cargo init
COPY Cargo.toml /code/Cargo.toml
RUN cargo fetch
COPY . /code

FROM base AS development

EXPOSE 8000

CMD [ "cargo", "run", "--offline" ]

FROM base AS builder

RUN cargo build --release --offline

FROM debian:buster-slim

ENV ROCKET_ENV=production

EXPOSE 8000

COPY --from=builder /code/target/release/react-rust-postgres /react-rust-postgres

CMD [ "/react-rust-postgres" ]
5 changes: 5 additions & 0 deletions react-rust-postgres/backend/diesel.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# For documentation on how to configure this file,
# see diesel.rs/guides/configuring-diesel-cli

[print_schema]
file = "src/schema.rs"
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.

DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.




-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE users;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
CREATE TABLE users (
id SERIAL PRIMARY KEY,
login TEXT UNIQUE NOT NULL
);
4 changes: 4 additions & 0 deletions react-rust-postgres/backend/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Backend

This backend is made with Rust using [Rocket](https://rocket.rs/) as a web server and [Diesel](https://diesel.rs/) as an ORM.

96 changes: 96 additions & 0 deletions react-rust-postgres/backend/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rocket_contrib;

mod schema;
mod user;

use rocket::config::{Config, Environment, Value};
use rocket::fairing::AdHoc;
use rocket_contrib::json::Json;
use std::collections::HashMap;
use std::env;

// This macro from `diesel_migrations` defines an `embedded_migrations` module
// containing a function named `run`. This allows the example to be run and
// tested without any outside setup of the database.
embed_migrations!();

#[database("my_db")]
struct MyDBConn(diesel::PgConnection);

#[derive(Serialize)]
struct HelloMessage {
message: String,
}

#[get("/")]
fn index(conn: MyDBConn) -> Json<HelloMessage> {
let result = match user::User::all(&*conn) {
Ok(res) => res.len(),
Err(_) => 0,
};

Json(HelloMessage {
message: format!("Hello with {} users", result),
})
}

fn get_config() -> Config {
let mut database_config = HashMap::new();
let mut databases = HashMap::new();

let env_address = env::var("ROCKET_ADDRESS")
.or::<String>(Ok(String::from("localhost")))
.unwrap();

let env_mode = env::var("ROCKET_ENV")
.or(Ok(String::from("development")))
.and_then(|value| value.parse::<Environment>())
.unwrap();

let database_url = match env::var("DATABASE_URL") {
Ok(value) => value,
Err(_) => String::from("postgres://localhost/postgres"),
};

database_config.insert("url", Value::from(database_url));
databases.insert("my_db", Value::from(database_config));

let config = Config::build(env_mode)
.address(env_address)
.extra("databases", databases)
.finalize()
.unwrap();

config
}

fn run_db_migrations(r: rocket::Rocket) -> Result<rocket::Rocket, rocket::Rocket> {
let conn = MyDBConn::get_one(&r).expect("database connection");
match embedded_migrations::run(&*conn) {
Ok(()) => Ok(r),
Err(e) => {
println!("Failed to run database migrations: {:?}", e);
Err(r)
}
}
}

fn main() {
let config = get_config();
rocket::custom(config)
.attach(MyDBConn::fairing())
.attach(AdHoc::on_attach("Database Migrations", run_db_migrations))
.mount("/", routes![index])
.launch();
}
6 changes: 6 additions & 0 deletions react-rust-postgres/backend/src/schema.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
table! {
users (id) {
id -> Int4,
login -> Text,
}
}
18 changes: 18 additions & 0 deletions react-rust-postgres/backend/src/user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#![allow(proc_macro_derive_resolution_fallback)]

use diesel;
use diesel::prelude::*;
use super::schema::users;

#[derive(Queryable, AsChangeset, Serialize, Deserialize)]
#[table_name = "users"]
pub struct User {
pub id: i32,
pub login: String,
}

impl User {
pub fn all(connection: &PgConnection) -> QueryResult<Vec<User>> {
users::table.load::<User>(&*connection)
}
}
Binary file added react-rust-postgres/capture.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 43 additions & 0 deletions react-rust-postgres/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
version: "3.7"
services:
frontend:
build:
context: frontend
target: development
networks:
- client-side
ports:
- 3000:3000
volumes:
- ./frontend/src:/code/src:ro
backend:
build:
context: backend
target: development
environment:
- DATABASE_URL=postgres://postgres:mysecretpassword@db/postgres
networks:
- client-side
- server-side
volumes:
- ./backend/src:/code/src
- backend-cache:/code/target
depends_on:
- db
db:
image: postgres:12-alpine
restart: always
environment:
- POSTGRES_PASSWORD=mysecretpassword
networks:
- server-side
ports:
- 5432:5432
volumes:
- db-data:/var/lib/postgresql/data
networks:
client-side: {}
server-side: {}
volumes:
backend-cache: {}
db-data: {}
2 changes: 2 additions & 0 deletions react-rust-postgres/frontend/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
build
23 changes: 23 additions & 0 deletions react-rust-postgres/frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
20 changes: 20 additions & 0 deletions react-rust-postgres/frontend/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
FROM node:lts AS development

ENV CI=true
ENV PORT=3000

WORKDIR /code
COPY package.json /code/package.json
COPY package-lock.json /code/package-lock.json
RUN npm ci
COPY . /code

CMD [ "npm", "start" ]

FROM development AS builder

RUN npm run build

FROM nginx:1.13-alpine

COPY --from=builder /code/build /usr/share/nginx/html
Loading

0 comments on commit 11c633b

Please sign in to comment.