Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webapp Basics merge from dev #2

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DATABASE_URL=postgres://code:spark@localhost/code_spark
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,8 @@ Cargo.lock

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb


# Added by cargo

/target
19 changes: 19 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#Cargo.toml
[package]
name = "code-spark"
version = "0.1.0"
edition = "2021"

[dependencies]
rocket = { version = "0.5.0-rc.2", features=["json"]}
diesel = { version = "2.0.0", features = ["postgres", "r2d2"] }
dotenvy = "0.15"
serde = "1.0.152"

[dependencies.rocket_dyn_templates]
features = ["handlebars"]

[dependencies.rocket_contrib]
version = "0.4.4"
default-features = false
features = ["json"]
9 changes: 9 additions & 0 deletions diesel.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli

[print_schema]
file = "src/schema.rs"
custom_type_derives = ["diesel::query_builder::QueryId"]

[migrations_directory]
dir = "migrations"
Empty file added migrations/.keep
Empty file.
6 changes: 6 additions & 0 deletions migrations/00000000000000_diesel_initial_setup/down.sql
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();
36 changes: 36 additions & 0 deletions migrations/00000000000000_diesel_initial_setup/up.sql
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;
1 change: 1 addition & 0 deletions migrations/2023-08-16-154540_users/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE user_account
6 changes: 6 additions & 0 deletions migrations/2023-08-16-154540_users/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE TABLE users (
id SERIAL PRIMARY KEY,
user_email VARCHAR(255) NOT NULL,
user_full_name VARCHAR(255) NOT NULL,
user_github_profile_name VARCHAR(255) NOT NULL
);
22 changes: 22 additions & 0 deletions sandbox/database.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
DROP DATABASE IF EXISTS code_spark;

CREATE DATABASE code_spark;

\c code_spark;

CREATE TABLE user_account (
id BIGSERIAL PRIMARY KEY,
user_email VARCHAR(255) NOT NULL,
user_full_name VARCHAR(255) NOT NULL,
user_github_profile_name (VARCHAR(255)) NOT NULL,
);

CREATE TABLE match_request (
id BIGSERIAL PRIMARY KEY,
match_request_sender_id VARCHAR(255) NOT NULL,
match_request_receiver_id VARCHAR(255) NOT NULL,
match_request_status INT NOT NULL,
created_date TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
accepted_date TIMESTAMPTZ
);

14 changes: 14 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
extern crate rocket;
use rocket::{launch, routes};
use rocket_dyn_templates::{ Template };
mod services;
pub mod models;
pub mod schema;

#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![services::create_user])
.mount("/", routes![services::list])
.attach(Template::fairing())
}
12 changes: 12 additions & 0 deletions src/models/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use super::schema::users;
use diesel::{prelude::*};
use serde::{Serialize, Deserialize};

#[derive(Queryable, Insertable, Serialize, Deserialize)]
#[diesel(table_name = users)]
pub struct User {
pub id: i32,
pub user_email: String,
pub user_full_name: String,
pub user_github_profile_name: String,
}
13 changes: 13 additions & 0 deletions src/schema.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// @generated automatically by Diesel CLI.

diesel::table! {
users (id) {
id -> Int4,
#[max_length = 255]
user_email -> Varchar,
#[max_length = 255]
user_full_name -> Varchar,
#[max_length = 255]
user_github_profile_name -> Varchar,
}
}
58 changes: 58 additions & 0 deletions src/services/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
extern crate diesel;
extern crate rocket;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use dotenvy::dotenv;
use rocket::response::{status::Created, Debug};
use rocket::serde::{json::Json, Deserialize, Serialize};
use rocket::{get, post };
use crate::models;
use crate::schema;
use rocket_dyn_templates::{context, Template};
use std::env;

pub fn establish_connection_pg() -> PgConnection {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
PgConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}

#[derive(Serialize, Deserialize)]
pub struct NewUser {
user_email: String,
user_full_name: String,
user_github_profile_name: String,
}

type Result<T, E = Debug<diesel::result::Error>> = std::result::Result<T, E>;

#[post("/users", format = "json", data = "<user>")]
pub fn create_user(user: Json<NewUser>) -> Result<Created<Json<NewUser>>> {
use models::User;
let connection = &mut establish_connection_pg();

let new_user = User {
id: 1,
user_email: user.user_email.to_string(),
user_full_name: user.user_full_name.to_string(),
user_github_profile_name: user.user_github_profile_name.to_string(),
};

diesel::insert_into(self::schema::users::dsl::users)
.values(&new_user)
.execute(connection)
.expect("Error saving new user");
Ok(Created::new("/").body(user))
}

#[get("/users")]
pub fn list() -> Template {
use self::models::User;
let connection = &mut establish_connection_pg();
let results = self::schema::users::dsl::users
.load::<User>(connection)
.expect("Error loading users");
Template::render("users", context! {users: &results, count: results.len()})
}

23 changes: 23 additions & 0 deletions templates/users.html.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog Posts</title>
</head>
<body>
<section id="hello">
<h1>Users</h1>
New Users
<ul>
{{#each users}}
<li>Name: {{ this.user_full_name }}</li>
<li>GitHub Profile Name: {{ this.user_github_profile_name }}</li>
{{else}}
<p> No posts yet</p>
{{/each}}
</ul>
</section>
</body>
</html>