From 8ae488341a66d27c91230b1c76d415d59c0e418b Mon Sep 17 00:00:00 2001 From: Akshay Date: Mon, 24 Aug 2020 10:09:53 +0530 Subject: refactor db to init once, open connections otherwise --- src/db.rs | 20 +++++++++++++++----- src/main.rs | 10 ++++++---- src/service.rs | 8 +++----- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/db.rs b/src/db.rs index 4025e12..299e07c 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,16 +1,26 @@ +// extern use anyhow::Result; use log::{debug, info}; use rusqlite::{Connection, OpenFlags, NO_PARAMS}; +// std use std::fmt; use std::path::Path; -pub fn init_db + fmt::Display>(p: P) -> Result { - debug!("Looking for database at `{}`", p); - let conn = Connection::open_with_flags( +pub fn open_connection

(p: P) -> Result +where + P: AsRef + fmt::Display, +{ + info!("Opened connection to databse"); + Ok(Connection::open_with_flags( &p, OpenFlags::SQLITE_OPEN_CREATE | OpenFlags::SQLITE_OPEN_READ_WRITE, - )?; + )?) +} + +pub fn init_db + fmt::Display>(p: P) -> Result<()> { + debug!("Looking for database at `{}`", p); + let conn = open_connection(&p)?; conn.execute( "CREATE TABLE IF NOT EXISTS urls ( link TEXT PRIMARY KEY, @@ -19,5 +29,5 @@ pub fn init_db + fmt::Display>(p: P) -> Result { NO_PARAMS, )?; info!("SQLite3 database `{}` initialized", &p); - return Ok(conn); + Ok(()) } diff --git a/src/main.rs b/src/main.rs index c9819d0..35e686e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,22 +1,24 @@ +// extern use anyhow::Result; use hyper::service::{make_service_fn, service_fn}; use hyper::Server; use log::trace; +// internal mod db; -use db::init_db; +use db::{init_db, open_connection}; + mod service; use service::shortner_service; -use std::sync::{Arc, Mutex}; - fn main() -> Result<()> { pretty_env_logger::init(); + init_db("./urls.db_3")?; smol::run(async { let addr = ([127, 0, 0, 1], 3000).into(); let service = make_service_fn(move |_| async { Ok::<_, hyper::Error>(service_fn(move |req| { - let db_conn = init_db("./urls.db_3").unwrap(); + let db_conn = open_connection("./urls.db_3").unwrap(); shortner_service(req, db_conn) })) }); diff --git a/src/service.rs b/src/service.rs index 41aa048..4477ee8 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1,3 +1,4 @@ +// extern use anyhow::{Context, Result}; use hyper::header::CONTENT_TYPE; use hyper::{Body, Method, Request, Response, StatusCode}; @@ -7,8 +8,8 @@ use nanoid::nanoid; use rusqlite::{params, Connection}; use url::form_urlencoded; +// std use std::collections::HashMap; -use std::sync::{Arc, Mutex}; fn respond_with_shortlink>(shortlink: S) -> Response { info!("Successfully generated shortlink"); @@ -90,10 +91,7 @@ async fn process_form(req: Request, conn: &mut Connection) -> Result, - mut conn: Arc>, -) -> Result> { +pub async fn shortner_service(req: Request, mut conn: Connection) -> Result> { match req.method() { &Method::POST => { let boundary = req -- cgit v1.2.3