Skip to content

Commit

Permalink
interaction between API and client
Browse files Browse the repository at this point in the history
  • Loading branch information
melnary committed May 7, 2020
1 parent 385fcdd commit 1e06820
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 25 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ crc32fast = "1.2.0"
base64 = "0.12.0"
url = "2.1.1"
diesel = { version = "1.4.4", features = ["postgres", "r2d2"] }
actix-files = "0.2.1"


12 changes: 7 additions & 5 deletions client/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,23 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Shor</title>
<link rel="stylesheet" href="main.css">
<script src="main.js"></script>
<title>Shorest</title>
<link rel="stylesheet" href="static/main.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/validate.js/0.13.1/validate.min.js"></script>
<script src="static/main.js"></script>
</head>
<body>
<div class="active">
<div class="title">
<a><b>sho.rest</b><br></a>
<a>Made with ❤ by <b>Mel</b></a>
</div>
<form class="form-inline" onsubmit="onFormSubmit(); return false;">
<form id="form">
<div class="input-group" id="form-group">
<div class="input-container">
<a class="input-field-text">https://</a>
<input oninput="inputUpdate()" pattern="(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?" class="input-field" id="url" required>
<input class="input-field" id="url" required>
</div>
<div class="btn-container">
<input type="submit" value="" class="btn">
Expand Down
13 changes: 0 additions & 13 deletions client/main.js

This file was deleted.

1 change: 1 addition & 0 deletions client/main.css → client/static/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ html * {
touch-action: manipulation;
cursor: pointer;
background-image: none;
background-color: #fff;
padding: 4px 5vw;
height: 10vh;
-webkit-user-select: none;
Expand Down
30 changes: 30 additions & 0 deletions client/static/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
$(document).ready(function() {
$('#form').on('submit', onFormSubmit);
$('#url').on({'input': inputUpdate, 'paste': pasteTrim});
});

function onFormSubmit() {
const urlField = document.getElementById('url');
const data = JSON.stringify({'url': 'https://' + urlField.value});
$.ajax('/', {method: 'POST', data: data, contentType: 'application/json'}).then(function (r) {
urlField.value = 'sho.rest/' + r.hash;
})
return false;
}

function inputUpdate() {
const userInput = document.getElementById('url').value;
if (!validate({website: 'https://' + userInput}, {website: {url: true}})) {
$('#form-group').css('border-color', '#E0E0E0');
} else {
$('#form-group').css('border-color', '#FFBCBC');
}
}

function pasteTrim() {
const pattern = /^https?:\/\//;
setTimeout(() => {
const element = $('#url');
element.value = element.value.replace(pattern, '');
}, 0);
}
16 changes: 9 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ use schema::links;
mod types;
use types::*;

use actix_web::{middleware, web, HttpServer, App, HttpResponse, Result};
use actix_web::{middleware, web, HttpServer, App, HttpResponse, Result, HttpRequest};
use actix_web::web::{Json, Path, Data};
use diesel::{PgConnection, RunQueryDsl, QueryDsl, ExpressionMethods, QueryResult};
use dotenv::dotenv;
use diesel::r2d2::{ConnectionManager, Pool};
use actix_files::{Files, NamedFile};

fn establish_connection() -> Pool<ConnectionManager<PgConnection>> {
dotenv().ok();
Expand Down Expand Up @@ -58,16 +59,14 @@ fn add_to_database_safely(mut hash: String, user_url: String, connection: &PgCon
}
}
Err(_) => {
if add_entry_to_database(Entry { hash: hash.clone() , url: user_url }, connection).is_err() {

}
add_entry_to_database(Entry { hash: hash.clone() , url: user_url }, connection).unwrap();
}
};
hash
}

async fn root() -> HttpResponse {
HttpResponse::Ok().body("Please make a POST request to / in the format {'url': '<your_url>'} with the URL you want to shorten!")
async fn root(req: HttpRequest) -> HttpResponse {
NamedFile::open("./client/index.html").unwrap().into_response(&req).unwrap()
}

async fn shorten(params: Json<UserData>, state: Data<PoolState>) -> HttpResponse {
Expand All @@ -77,7 +76,7 @@ async fn shorten(params: Json<UserData>, state: Data<PoolState>) -> HttpResponse
return HttpResponse::BadRequest().body("The URL you entered does not follow the proper URL format.");
},
};
let hash= add_to_database_safely(get_hash_from_string(&user_url), user_url, &state.get().expect("Could not get a connection from pool"));
let hash = add_to_database_safely(get_hash_from_string(&user_url), user_url, &state.get().expect("Could not get a connection from pool"));

HttpResponse::Ok().json(UserResponse{ hash })
}
Expand Down Expand Up @@ -109,6 +108,9 @@ async fn main() -> std::io::Result<()> {
web::resource("/{hash}")
.route(web::get().to(redirect))
)
.service(
Files::new("/static/", "./client/static/")
)
})
.bind("localhost:3000")?
.run()
Expand Down

0 comments on commit 1e06820

Please sign in to comment.