feat: remove graphql and migrate web framework to actix-web alpha for using stable rust

This commit is contained in:
Kilerd Chan 2019-04-18 17:27:21 +08:00
parent 78484a8e00
commit ca2f00fc3c
13 changed files with 55 additions and 164 deletions

View File

@ -7,8 +7,6 @@ license = "MIT"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
rocket = "0.4.0"
rocket_contrib = { version = "0.4.0", default-features = true, features = ["tera_templates"] }
diesel = { version = "1.3.3", features = ["postgres", "r2d2", "chrono"] } diesel = { version = "1.3.3", features = ["postgres", "r2d2", "chrono"] }
dotenv = "0.9.0" dotenv = "0.9.0"
r2d2 = "0.8" r2d2 = "0.8"
@ -19,8 +17,8 @@ tera = "*"
pulldown-cmark = { version = "0.1.2", default-features = false } pulldown-cmark = { version = "0.1.2", default-features = false }
chrono = { version = "*", features = ["serde"] } chrono = { version = "*", features = ["serde"] }
rust-crypto = "^0.2" rust-crypto = "^0.2"
juniper = "0.11.1"
juniper_codegen = "0.11.1"
juniper_rocket = "0.2.0"
rand = "0.6.0"
rss = "1.6.1" rss = "1.6.1"
actix-web="1.0.0-alpha.6"
actix = "0.8.1"
diesel_migrations = "1.4.0"

View File

@ -1,22 +0,0 @@
use crate::schema::{setting};
#[derive(GraphQLInputObject)]
#[graphql(description="modify a setting")]
#[derive(Serialize, Insertable, AsChangeset)]
#[table_name = "setting"]
pub struct SettingInput {
#[graphql(description="the name of the setting")]
pub name: String,
#[graphql(description="new value of the setting")]
pub value: String,
}
#[derive(GraphQLInputObject)]
#[graphql(description="delete article")]
pub struct DeleteArticleInput {
#[graphql(description="id of article wanna delete")]
pub id: i32,
}

View File

@ -1,17 +0,0 @@
use juniper::RootNode;
use juniper::Context;
pub mod model;
pub mod input;
pub mod query;
pub mod mutation;
use crate::pg_pool::DbConn;
pub struct Query;
pub struct Mutation;
impl Context for DbConn {}
pub type Schema = RootNode<'static, Query, Mutation>;

View File

@ -1,7 +0,0 @@
#[derive(GraphQLEnum)]
pub enum ArticlePublishStatus {
Published,
UnPublished,
All
}

View File

@ -1,18 +0,0 @@
use crate::graphql::Mutation;
use crate::pg_pool::DbConn;
use crate::graphql::input::*;
use crate::models::{Setting, Article};
graphql_object!(Mutation: DbConn |&self| {
field modifySetting(&executor, input: SettingInput) -> Option<Setting> {
let conn = executor.context();
Setting::modify(&input, &conn)
}
field deleteArticle(&executor, input: DeleteArticleInput) -> bool {
let conn = executor.context();
Article::delete(input.id, &conn)
}
});

View File

@ -1,17 +0,0 @@
use crate::graphql::Query;
use crate::pg_pool::DbConn;
use crate::models::Article;
use crate::graphql::model::*;
graphql_object!(Query: DbConn |&self| {
description: "The root query object of the schema"
field users(&executor) -> Vec<i32> as "AllUsers" {
vec![1, 3, 4]
}
field articles(&executor, article_status: Option<ArticlePublishStatus>) -> Vec<Article> as "all article" {
let db_conn = executor.context();
Article::load_all(true, &db_conn)
}
});

View File

@ -1,76 +1,46 @@
#![feature(proc_macro_hygiene,decl_macro, custom_attribute, plugin)] #![feature(proc_macro_hygiene, decl_macro, custom_attribute, plugin)]
extern crate chrono;
extern crate crypto;
#[macro_use] #[macro_use]
extern crate diesel; extern crate diesel;
extern crate dotenv;
#[macro_use]
extern crate juniper;
#[macro_use]
extern crate juniper_codegen;
extern crate juniper_rocket;
extern crate pulldown_cmark;
extern crate r2d2;
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate tera;
extern crate rand;
use actix_web::{
middleware::{cors::Cors, Logger},
App, HttpServer,
};
use diesel_migrations::embed_migrations;
use dotenv::dotenv; use dotenv::dotenv;
use rocket_contrib::templates::Template;
use crate::pg_pool::database_pool_establish;
mod guard; mod guard;
mod models; mod models;
mod modelss;
mod pg_pool; mod pg_pool;
mod request; mod request;
mod response; mod response;
mod routers; mod routers;
mod schema; mod schema;
mod graphql;
use crate::graphql::{Schema, Query, Mutation}; embed_migrations!();
fn main() { fn main() -> std::io::Result<()> {
use crate::routers::{admin, article, catacher, graphql, rss}; let sys = actix::System::new("lemmy");
dotenv().ok(); dotenv().ok();
let database_url = std::env::var("DATABASE_URL").expect("database_url must be set"); let database_url = std::env::var("DATABASE_URL").expect("database_url must be set");
let pool = database_pool_establish(&database_url);
rocket::ignite() embed_migrations::run(&poll.get());
.register(catchers![
catacher::not_found_catcher,
catacher::unauthorized,
])
.manage(pg_pool::init(&database_url))
.manage(Schema::new(Query{}, Mutation{}))
.mount("/", routes![
article::index,
article::single_article,
article::get_article_by_url,
article::static_content,
rss::rss, HttpServer::new(move || {
App::new()
.data(pool)
.wrap(Logger::default())
.wrap(Cors::default())
})
.bind(("127.0.0.1", 8000))?
.system_exit()
.start();
graphql::graphql_authorization, sys.run();
graphql::graphiql, Ok(())
graphql::get_graphql_handler,
graphql::post_graphql_handler
])
.mount("/admin", routes![
admin::admin_login,
admin::admin_authentication,
admin::admin_index,
admin::article_edit,
admin::save_article,
admin::delete_article,
admin::article_creation,
admin::change_password,
admin::change_setting
])
.attach(Template::fairing())
.launch();
} }

10
src/models/article.rs Normal file
View File

@ -0,0 +1,10 @@
#[derive(Queryable, Debug, Serialize, Insertable, AsChangeset, GraphQLObject)]
pub struct Article {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
pub user_id: i32,
pub publish_at: NaiveDateTime,
pub url: Option<String>,
}

10
src/models/mod.rs Normal file
View File

@ -0,0 +1,10 @@
use diesel::pg::{Pg, PgConnection};
use diesel::result::Error;
pub trait CRUD<CreatedModel, UpdateModel, PK> {
fn create(conn: &PgConnection, from: &CreatedModel) -> Result<Self, Error>;
fn read(conn: &PgConnection) -> Vec<Self>;
fn update(conn: &PgConnection, pk: PK, value: &UpdateModel) -> Result<Self, Error>;
fn delete(conn: &PgConnection, pk: PK) -> Result<usize, Error>;
fn get_by_pk(conn: &PgConnection, pk: PK) -> Result<Self, Error>;
}

0
src/models/setting.rs Normal file
View File

0
src/models/user.rs Normal file
View File

View File

@ -9,25 +9,9 @@ use rocket::http::Status;
use rocket::request::{self, FromRequest}; use rocket::request::{self, FromRequest};
use rocket::{Outcome, Request, State}; use rocket::{Outcome, Request, State};
use std::ops::Deref; use std::ops::Deref;
/// Db Connection request guard type: wrapper around r2d2 pooled connection
pub struct DbConn(pub r2d2::PooledConnection<ManagedPgConn>); pub struct DbConn(pub r2d2::PooledConnection<ManagedPgConn>);
/// Attempts to retrieve a single connection from the managed database pool. If
/// no pool is currently managed, fails with an `InternalServerError` status. If
/// no connections are available, fails with a `ServiceUnavailable` status.
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<DbConn, ()> {
let pool = request.guard::<State<Pool>>()?;
match pool.get() {
Ok(conn) => Outcome::Success(DbConn(conn)),
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
}
}
}
// For the convenience of using an &DbConn as an &SqliteConnection.
impl Deref for DbConn { impl Deref for DbConn {
type Target = PgConnection; type Target = PgConnection;
@ -36,7 +20,7 @@ impl Deref for DbConn {
} }
} }
pub fn init(database_url: &str) -> Pool { pub fn database_pool_establish(database_url: &str) -> Pool {
let manager = ConnectionManager::<PgConnection>::new(database_url); let manager = ConnectionManager::<PgConnection>::new(database_url);
r2d2::Pool::new(manager).expect("Failed to create pool.") r2d2::Pool::new(manager).expect("Failed to create pool.")
} }