cargo fmt
Signed-off-by: ATechnoHazard <amolele@gmail.com>
This commit is contained in:
parent
1aa0c5c278
commit
62df3f239a
@ -1,34 +1,47 @@
|
||||
use rocket::Rocket;
|
||||
use rocket::response::status;
|
||||
use rocket::http::Status;
|
||||
use rocket::response::status;
|
||||
use rocket::Rocket;
|
||||
use rocket_contrib::json::Json;
|
||||
use serde_json::Value;
|
||||
|
||||
#[catch(404)]
|
||||
fn not_found() -> status::Custom<Json<Value>> {
|
||||
status::Custom(Status::NotFound, Json(json!({
|
||||
"err":"route not found",
|
||||
"msg": "The given route does not exist"
|
||||
})))
|
||||
status::Custom(
|
||||
Status::NotFound,
|
||||
Json(json!({
|
||||
"err":"route not found",
|
||||
"msg": "The given route does not exist"
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
#[catch(422)]
|
||||
fn unprocessable_entity() -> status::Custom<Json<Value>> {
|
||||
status::Custom(Status::UnprocessableEntity, Json(json!({
|
||||
"err":"failed to process entity",
|
||||
"msg": "The given object could not be processed. This could be due to sending \
|
||||
malformed or incomplete JSON objects in the request body."
|
||||
})))
|
||||
status::Custom(
|
||||
Status::UnprocessableEntity,
|
||||
Json(json!({
|
||||
"err":"failed to process entity",
|
||||
"msg": "The given object could not be processed. This could be due to sending \
|
||||
malformed or incomplete JSON objects in the request body."
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
#[catch(500)]
|
||||
fn internal_server_error() -> status::Custom<Json<Value>> {
|
||||
status::Custom(Status::NotFound, Json(json!({
|
||||
"err":"internal server error",
|
||||
"msg": "Something went wrong, try again"
|
||||
})))
|
||||
status::Custom(
|
||||
Status::NotFound,
|
||||
Json(json!({
|
||||
"err":"internal server error",
|
||||
"msg": "Something went wrong, try again"
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn fuel(rocket: Rocket) -> Rocket {
|
||||
rocket.register(catchers![not_found, unprocessable_entity, internal_server_error])
|
||||
}
|
||||
rocket.register(catchers![
|
||||
not_found,
|
||||
unprocessable_entity,
|
||||
internal_server_error
|
||||
])
|
||||
}
|
||||
|
@ -1,9 +1,9 @@
|
||||
use diesel::PgConnection;
|
||||
use diesel::r2d2::{PooledConnection, ConnectionManager};
|
||||
use rocket::{Request, request, State, Outcome};
|
||||
use rocket::request::FromRequest;
|
||||
use rocket::http::Status;
|
||||
use crate::utils::db::Pool;
|
||||
use diesel::r2d2::{ConnectionManager, PooledConnection};
|
||||
use diesel::PgConnection;
|
||||
use rocket::http::Status;
|
||||
use rocket::request::FromRequest;
|
||||
use rocket::{request, Outcome, Request, State};
|
||||
use std::ops::Deref;
|
||||
|
||||
pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>);
|
||||
@ -26,4 +26,4 @@ impl Deref for DbConn {
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1 +1 @@
|
||||
pub mod db;
|
||||
pub mod db;
|
||||
|
@ -0,0 +1 @@
|
||||
|
@ -1,5 +1,5 @@
|
||||
pub mod routes;
|
||||
pub mod catchers;
|
||||
pub mod routes;
|
||||
|
||||
mod guards;
|
||||
mod misc;
|
||||
|
@ -1,9 +1,10 @@
|
||||
use rocket::{Rocket};
|
||||
use rocket::Rocket;
|
||||
|
||||
#[get("/")]
|
||||
fn check() -> &'static str { "OK" }
|
||||
|
||||
fn check() -> &'static str {
|
||||
"OK"
|
||||
}
|
||||
|
||||
pub fn fuel(rocket: Rocket) -> Rocket {
|
||||
rocket.mount("/api/health", routes![check])
|
||||
}
|
||||
}
|
||||
|
@ -10,4 +10,3 @@ pub fn fuel(rocket: Rocket) -> Rocket {
|
||||
rocket = paste::fuel(rocket);
|
||||
rocket
|
||||
}
|
||||
|
||||
|
@ -1,14 +1,18 @@
|
||||
use std::ops::DerefMut;
|
||||
|
||||
use rocket::{http::{Cookie, Cookies, Status}, response::status, Rocket};
|
||||
use rocket::response::status::Custom;
|
||||
use rocket::{
|
||||
http::{Cookie, Cookies, Status},
|
||||
response::status,
|
||||
Rocket,
|
||||
};
|
||||
use rocket_contrib::json::Json;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::core::paste::{entity::Paste, service::create_paste, service::fetch_paste};
|
||||
use crate::core::users::{service::create_or_fetch_user};
|
||||
use crate::utils::phonetic_key;
|
||||
use crate::api::guards::db;
|
||||
use crate::core::paste::{entity::Paste, service::create_paste, service::fetch_paste};
|
||||
use crate::core::users::service::create_or_fetch_user;
|
||||
use crate::utils::phonetic_key;
|
||||
|
||||
use diesel::result::Error;
|
||||
|
||||
@ -27,10 +31,15 @@ fn create(mut paste: Json<Paste>, conn: db::DbConn, mut ck: Cookies) -> Custom<J
|
||||
// Create or fetch already existing user
|
||||
let user = match create_or_fetch_user(user_id, &conn) {
|
||||
Ok(user) => user,
|
||||
Err(e) => return status::Custom(Status::InternalServerError, Json(json!({
|
||||
"err": e.to_string(),
|
||||
"msg": "Failed to create or fetch user"
|
||||
})))
|
||||
Err(e) => {
|
||||
return status::Custom(
|
||||
Status::InternalServerError,
|
||||
Json(json!({
|
||||
"err": e.to_string(),
|
||||
"msg": "Failed to create or fetch user"
|
||||
})),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let new_paste = paste.deref_mut();
|
||||
@ -41,18 +50,20 @@ fn create(mut paste: Json<Paste>, conn: db::DbConn, mut ck: Cookies) -> Custom<J
|
||||
new_paste.belongs_to = Some(user.id);
|
||||
|
||||
match create_paste(new_paste, &conn) {
|
||||
Ok(_) => {
|
||||
status::Custom(Status::Created, Json(json!({
|
||||
"msg": "Successfully created paste",
|
||||
"paste_id": new_paste.id
|
||||
})))
|
||||
}
|
||||
Err(e) => {
|
||||
status::Custom(Status::InternalServerError, Json(json!({
|
||||
Ok(_) => status::Custom(
|
||||
Status::Created,
|
||||
Json(json!({
|
||||
"msg": "Successfully created paste",
|
||||
"paste_id": new_paste.id
|
||||
})),
|
||||
),
|
||||
Err(e) => status::Custom(
|
||||
Status::InternalServerError,
|
||||
Json(json!({
|
||||
"err": e.to_string(),
|
||||
"msg": "Failed to create paste"
|
||||
})))
|
||||
}
|
||||
})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,14 +73,20 @@ fn fetch(id: String, conn: db::DbConn) -> Custom<Json<Value>> {
|
||||
Ok(paste) => paste,
|
||||
Err(err) => {
|
||||
return match err.downcast_ref::<Error>() {
|
||||
Some(Error::NotFound) => Custom(Status::NotFound, Json(json!({
|
||||
"err": err.to_string(),
|
||||
"msg": "Unable to find a paste with that ID"
|
||||
}))),
|
||||
_ => Custom(Status::InternalServerError, Json(json!({
|
||||
"err": err.to_string(),
|
||||
"msg": "Something went wrong, try again"
|
||||
})))
|
||||
Some(Error::NotFound) => Custom(
|
||||
Status::NotFound,
|
||||
Json(json!({
|
||||
"err": err.to_string(),
|
||||
"msg": "Unable to find a paste with that ID"
|
||||
})),
|
||||
),
|
||||
_ => Custom(
|
||||
Status::InternalServerError,
|
||||
Json(json!({
|
||||
"err": err.to_string(),
|
||||
"msg": "Something went wrong, try again"
|
||||
})),
|
||||
),
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -79,4 +96,4 @@ fn fetch(id: String, conn: db::DbConn) -> Custom<Json<Value>> {
|
||||
|
||||
pub fn fuel(rocket: Rocket) -> Rocket {
|
||||
rocket.mount("/api/paste", routes![create, fetch])
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1 @@
|
||||
|
@ -1,2 +1,2 @@
|
||||
pub mod paste;
|
||||
pub mod users;
|
||||
pub mod users;
|
||||
|
@ -7,4 +7,4 @@ pub struct Paste {
|
||||
pub belongs_to: Option<String>,
|
||||
pub is_url: bool,
|
||||
pub content: String,
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,3 @@
|
||||
pub mod entity;
|
||||
pub mod postgres;
|
||||
pub mod service;
|
||||
pub mod service;
|
||||
|
@ -16,4 +16,4 @@ pub fn create_paste(paste: &Paste, conn: &PgConnection) -> Result<usize> {
|
||||
pub fn fetch_paste(id: String, conn: &PgConnection) -> Result<Paste> {
|
||||
let paste = pastes::table.find(id).get_result::<Paste>(conn)?;
|
||||
Ok(paste)
|
||||
}
|
||||
}
|
||||
|
@ -11,4 +11,4 @@ pub fn create_paste(paste: &mut Paste, conn: &PgConnection) -> Result<usize> {
|
||||
|
||||
pub fn fetch_paste(id: String, conn: &PgConnection) -> Result<Paste> {
|
||||
postgres::fetch_paste(id, conn)
|
||||
}
|
||||
}
|
||||
|
@ -7,4 +7,4 @@ pub struct User {
|
||||
pub username: Option<String>,
|
||||
pub password: Option<String>,
|
||||
pub activated: Option<bool>,
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,3 @@
|
||||
pub mod postgres;
|
||||
pub mod entity;
|
||||
pub mod service;
|
||||
pub mod postgres;
|
||||
pub mod service;
|
||||
|
@ -1,6 +1,6 @@
|
||||
use diesel::prelude::*;
|
||||
use diesel::pg::PgConnection;
|
||||
use anyhow::Result;
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::prelude::*;
|
||||
|
||||
use crate::core::users::entity::User;
|
||||
use crate::schema::users;
|
||||
@ -16,4 +16,4 @@ pub fn create_user(user: &User, conn: &PgConnection) -> Result<usize> {
|
||||
pub fn find_user(id: String, conn: &PgConnection) -> Result<User> {
|
||||
let user = users::table.find(id).get_result::<User>(conn)?;
|
||||
Ok(user)
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
use anyhow::Result;
|
||||
use bcrypt::{DEFAULT_COST, hash};
|
||||
use bcrypt::{hash, DEFAULT_COST};
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::result::Error;
|
||||
|
||||
@ -16,21 +16,19 @@ pub fn create_user(user: &mut User, conn: &PgConnection) -> Result<usize> {
|
||||
pub fn create_or_fetch_user(id: String, conn: &PgConnection) -> Result<User> {
|
||||
let user = match postgres::find_user(id.clone(), conn) {
|
||||
Ok(user) => user,
|
||||
Err(err) => {
|
||||
match err.downcast_ref::<Error>() {
|
||||
Some(Error::NotFound) => {
|
||||
let new_user = User {
|
||||
id: id.clone(),
|
||||
username: None,
|
||||
password: None,
|
||||
activated: Some(false),
|
||||
};
|
||||
postgres::create_user(&new_user, conn)?;
|
||||
new_user
|
||||
}
|
||||
_ => return Err(err)
|
||||
Err(err) => match err.downcast_ref::<Error>() {
|
||||
Some(Error::NotFound) => {
|
||||
let new_user = User {
|
||||
id: id.clone(),
|
||||
username: None,
|
||||
password: None,
|
||||
activated: Some(false),
|
||||
};
|
||||
postgres::create_user(&new_user, conn)?;
|
||||
new_user
|
||||
}
|
||||
}
|
||||
_ => return Err(err),
|
||||
},
|
||||
};
|
||||
Ok(user)
|
||||
}
|
||||
}
|
||||
|
11
src/main.rs
11
src/main.rs
@ -16,12 +16,12 @@ extern crate slog;
|
||||
|
||||
pub mod api;
|
||||
pub mod core;
|
||||
pub mod utils;
|
||||
pub mod schema;
|
||||
pub mod utils;
|
||||
|
||||
use slog_term;
|
||||
use slog_async;
|
||||
use slog::{Drain, Logger};
|
||||
use slog_async;
|
||||
use slog_term;
|
||||
|
||||
embed_migrations!("migrations");
|
||||
|
||||
@ -32,7 +32,6 @@ fn run_migrations(logger: &Logger) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
dotenv::dotenv().ok();
|
||||
|
||||
@ -48,7 +47,5 @@ fn main() {
|
||||
rocket = api::routes::fuel(rocket);
|
||||
rocket = api::catchers::fuel(rocket);
|
||||
|
||||
rocket.manage(utils::db::pool())
|
||||
.manage(logger)
|
||||
.launch();
|
||||
rocket.manage(utils::db::pool()).manage(logger).launch();
|
||||
}
|
||||
|
@ -18,7 +18,4 @@ table! {
|
||||
|
||||
joinable!(pastes -> users (belongs_to));
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
pastes,
|
||||
users,
|
||||
);
|
||||
allow_tables_to_appear_in_same_query!(pastes, users,);
|
||||
|
@ -1,6 +1,6 @@
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::{r2d2, Connection};
|
||||
use diesel::r2d2::ConnectionManager;
|
||||
use diesel::{r2d2, Connection};
|
||||
use std::env;
|
||||
|
||||
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||
@ -16,4 +16,4 @@ fn database_url() -> String {
|
||||
|
||||
pub fn pg_connection() -> PgConnection {
|
||||
PgConnection::establish(database_url().as_str()).unwrap()
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,13 @@
|
||||
use rocket::{http::{Status, ContentType}, response::Responder, Request, response, Response, Outcome, State};
|
||||
use rocket::{
|
||||
http::{ContentType, Status},
|
||||
response,
|
||||
response::Responder,
|
||||
Outcome, Request, Response, State,
|
||||
};
|
||||
|
||||
use std::io::Cursor;
|
||||
use slog::Logger;
|
||||
use slog;
|
||||
use slog::Logger;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
pub enum ErrorCode {
|
||||
@ -32,14 +37,12 @@ impl Error {
|
||||
Error {
|
||||
code,
|
||||
msg: "".to_string(),
|
||||
}.set_msg()
|
||||
}
|
||||
.set_msg()
|
||||
}
|
||||
|
||||
pub fn custom(code: ErrorCode, msg: String) -> Error {
|
||||
Error {
|
||||
code,
|
||||
msg,
|
||||
}
|
||||
Error { code, msg }
|
||||
}
|
||||
|
||||
fn get_status_code(&self) -> Status {
|
||||
@ -56,14 +59,16 @@ impl Error {
|
||||
ErrorCode::NotAuthorized => Status::Forbidden,
|
||||
ErrorCode::CorruptResource => Status::InternalServerError,
|
||||
ErrorCode::LogicalConflict => Status::BadRequest,
|
||||
ErrorCode::Unknown => Status::InternalServerError
|
||||
ErrorCode::Unknown => Status::InternalServerError,
|
||||
}
|
||||
}
|
||||
|
||||
fn set_msg(mut self) -> Self {
|
||||
self.msg = match self.code.clone() {
|
||||
ErrorCode::InvalidCredentials => "invalid credentials were provided".to_string(),
|
||||
ErrorCode::MultipleAuthToken => "multiple authorization tokens were provided".to_string(),
|
||||
ErrorCode::MultipleAuthToken => {
|
||||
"multiple authorization tokens were provided".to_string()
|
||||
}
|
||||
ErrorCode::NoAuthToken => "no authorization token was found".to_string(),
|
||||
ErrorCode::AuthTokenCreationFailed => "authorization token creation failed".to_string(),
|
||||
ErrorCode::MalformedAuthToken => "authorization token was malformed".to_string(),
|
||||
@ -71,10 +76,14 @@ impl Error {
|
||||
ErrorCode::ResourceAlreadyExists => "the given resource already exists".to_string(),
|
||||
ErrorCode::DatabaseError => "database error occured".to_string(),
|
||||
ErrorCode::InvalidData => "invalid data provided".to_string(),
|
||||
ErrorCode::NotAuthorized => "you are not authorized to perform the requested operation".to_string(),
|
||||
ErrorCode::NotAuthorized => {
|
||||
"you are not authorized to perform the requested operation".to_string()
|
||||
}
|
||||
ErrorCode::CorruptResource => "requested resource was corrupted".to_string(),
|
||||
ErrorCode::LogicalConflict => "the request logically conflicts with the existing data".to_string(),
|
||||
ErrorCode::Unknown => "unknown error occured".to_string()
|
||||
ErrorCode::LogicalConflict => {
|
||||
"the request logically conflicts with the existing data".to_string()
|
||||
}
|
||||
ErrorCode::Unknown => "unknown error occured".to_string(),
|
||||
};
|
||||
self
|
||||
}
|
||||
@ -94,4 +103,4 @@ impl<'r> Responder<'r> for Error {
|
||||
.sized_body(Cursor::new(serde_json::to_string(&self).unwrap()))
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,3 @@
|
||||
pub mod errors;
|
||||
pub mod db;
|
||||
pub mod phonetic_key;
|
||||
pub mod errors;
|
||||
pub mod phonetic_key;
|
||||
|
@ -17,4 +17,4 @@ use uuid::Uuid;
|
||||
|
||||
pub fn get_random_id() -> String {
|
||||
Uuid::new_v4().to_string()
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user