Compare commits
1 Commits
Author | SHA1 | Date | |
---|---|---|---|
4970e2570a |
5
.env
5
.env
@ -1 +1,4 @@
|
||||
DATABASE_URL=postgres://postgres:password@localhost/olh
|
||||
APP_ENV=development
|
||||
APP_LOKI_ENDPOINT=http://localhost:3100/loki/api/v1/push
|
||||
APP_LOG_LEVEL=info
|
||||
APP_PORT=3000
|
||||
|
21
.gitignore
vendored
21
.gitignore
vendored
@ -1,22 +1 @@
|
||||
/target
|
||||
/migration/target
|
||||
|
||||
# Added by cargo
|
||||
#
|
||||
# already existing elements were commented out
|
||||
|
||||
#/target
|
||||
|
||||
|
||||
# Added by cargo
|
||||
#
|
||||
# already existing elements were commented out
|
||||
|
||||
#/target
|
||||
|
||||
|
||||
# Added by cargo
|
||||
#
|
||||
# already existing elements were commented out
|
||||
|
||||
#/target
|
||||
|
1510
Cargo.lock
generated
1510
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
11
Cargo.toml
11
Cargo.toml
@ -2,10 +2,11 @@
|
||||
name = "openlayerhub"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
build = "build.rs"
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
[dependencies]
|
||||
actix-web = "4.9.0"
|
||||
diesel = { version = "2.2.7", features = ["postgres", "r2d2"] }
|
||||
dotenv = "0.15.0"
|
||||
serde = { version = "1.0.218", features = ["derive"] }
|
||||
serde_json = "1.0.139"
|
||||
config = "0.15.7"
|
||||
dotenvy = "0.15.7"
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
|
46
build.rs
Normal file
46
build.rs
Normal file
@ -0,0 +1,46 @@
|
||||
use std::env;
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
let is_production = env::var("APP_ENV")
|
||||
.map(|e| e == "production")
|
||||
.unwrap_or(false);
|
||||
|
||||
let version = if is_production {
|
||||
get_latest_tag().unwrap_or_else(|| panic!("Production builds must have a GIT tag."))
|
||||
} else {
|
||||
get_commit_hash().unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string())
|
||||
};
|
||||
|
||||
println!("cargo:rustc-env=GIT_VERSION={}", version)
|
||||
}
|
||||
|
||||
fn get_commit_hash() -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(&["rev-parse", "--short=8", "HEAD"])
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
.map(|s| s.trim().to_string())
|
||||
}
|
||||
|
||||
fn get_latest_tag() -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(&["describe", "--tags", "--match", "v*"])
|
||||
.output()
|
||||
.ok()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
.map(|s| s.trim().to_string())
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
# 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", "Clone"]
|
||||
|
||||
[migrations_directory]
|
||||
dir = "migrations"
|
@ -1,6 +0,0 @@
|
||||
-- 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();
|
@ -1,36 +0,0 @@
|
||||
-- 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 +0,0 @@
|
||||
DROP TABLE users;
|
@ -1,5 +0,0 @@
|
||||
CREATE TABLE users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR NOT NULL,
|
||||
email VARCHAR NOT NULL UNIQUE
|
||||
);
|
1
src/config/mod.rs
Normal file
1
src/config/mod.rs
Normal file
@ -0,0 +1 @@
|
||||
pub mod parameter;
|
63
src/config/parameter.rs
Normal file
63
src/config/parameter.rs
Normal file
@ -0,0 +1,63 @@
|
||||
use config::{Config, ConfigError, Environment, File};
|
||||
use dotenvy::dotenv;
|
||||
use serde::Deserialize;
|
||||
use std::env;
|
||||
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
pub struct AppConfig {
|
||||
pub loki_endpoint: String,
|
||||
pub service_name: String,
|
||||
pub service_version: String,
|
||||
pub log_level: String,
|
||||
pub port: u16,
|
||||
pub environment: String,
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
pub fn new() -> Result<Self, ConfigError> {
|
||||
let _ = dotenv().ok();
|
||||
|
||||
let environment = env::var("APP_ENV").unwrap_or_else(|_| "development".into());
|
||||
|
||||
let config = Config::builder()
|
||||
// Start with default values
|
||||
.set_default("environment", &*environment)?
|
||||
.set_default("service_name", "OpenLayersHub")?
|
||||
.set_default("service_version", env!("GIT_VERSION"))?
|
||||
.set_default("log_level", "info")?
|
||||
.set_default("port", 3000)?
|
||||
// Add environment-specific config file
|
||||
.add_source(File::with_name(&format!("config/{}", environment)).required(false))
|
||||
.add_source(File::with_name(".env").required(false))
|
||||
.add_source(
|
||||
Environment::with_prefix("APP")
|
||||
.prefix_separator("_")
|
||||
.separator("__"),
|
||||
)
|
||||
.build()?;
|
||||
|
||||
config.try_deserialize()
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> Result<(), Vec<String>> {
|
||||
let mut errors = Vec::new();
|
||||
|
||||
if self.loki_endpoint.is_empty() {
|
||||
errors.push("Loki endpoint must be set".to_string());
|
||||
}
|
||||
|
||||
// Validate environment value
|
||||
if !["development", "staging", "production"].contains(&self.environment.as_str()) {
|
||||
errors.push(format!(
|
||||
"Invalid environment '{}'. Must be one of: development, staging, production",
|
||||
self.environment
|
||||
));
|
||||
}
|
||||
|
||||
if errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(errors)
|
||||
}
|
||||
}
|
||||
}
|
@ -1,88 +0,0 @@
|
||||
use actix_web::{web, HttpResponse, Responder};
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::r2d2::{self, ConnectionManager};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::r#trait::CrudEntity;
|
||||
|
||||
type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Pagination {
|
||||
limit: Option<i64>,
|
||||
offset: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn get_all<T: CrudEntity>(
|
||||
pool: web::Data<DbPool>,
|
||||
query: web::Query<Pagination>,
|
||||
) -> impl Responder {
|
||||
let mut conn = match pool.get() {
|
||||
Ok(conn) => conn,
|
||||
Err(_) => return HttpResponse::InternalServerError().finish(),
|
||||
};
|
||||
match T::find_all(&mut conn, query.limit, query.offset) {
|
||||
Ok(items) => HttpResponse::Ok().json(items),
|
||||
Err(_) => HttpResponse::InternalServerError().finish(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_one<T: CrudEntity>(
|
||||
pool: web::Data<DbPool>,
|
||||
id: web::Path<T::Id>,
|
||||
) -> impl Responder {
|
||||
let mut conn = match pool.get() {
|
||||
Ok(conn) => conn,
|
||||
Err(_) => return HttpResponse::InternalServerError().finish(),
|
||||
};
|
||||
match T::find_by_id(&mut conn, id.into_inner()) {
|
||||
Ok(item) => HttpResponse::Ok().json(item),
|
||||
Err(diesel::result::Error::NotFound) => HttpResponse::NotFound().finish(),
|
||||
Err(_) => HttpResponse::InternalServerError().finish(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create<T: CrudEntity>(
|
||||
pool: web::Data<DbPool>,
|
||||
item: web::Json<T::CreateInput>,
|
||||
) -> impl Responder {
|
||||
let mut conn = match pool.get() {
|
||||
Ok(conn) => conn,
|
||||
Err(_) => return HttpResponse::InternalServerError().finish(),
|
||||
};
|
||||
match T::insert(&mut conn, item.into_inner()) {
|
||||
Ok(created) => HttpResponse::Created().json(created),
|
||||
Err(_) => HttpResponse::InternalServerError().finish(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update<T: CrudEntity>(
|
||||
pool: web::Data<DbPool>,
|
||||
id: web::Path<T::Id>,
|
||||
item: web::Json<T::UpdateInput>,
|
||||
) -> impl Responder {
|
||||
let mut conn = match pool.get() {
|
||||
Ok(conn) => conn,
|
||||
Err(_) => return HttpResponse::InternalServerError().finish(),
|
||||
};
|
||||
match T::update(&mut conn, id.into_inner(), item.into_inner()) {
|
||||
Ok(updated) => HttpResponse::Ok().json(updated),
|
||||
Err(diesel::result::Error::NotFound) => HttpResponse::NotFound().finish(),
|
||||
Err(_) => HttpResponse::InternalServerError().finish(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete<T: CrudEntity>(
|
||||
pool: web::Data<DbPool>,
|
||||
id: web::Path<T::Id>,
|
||||
) -> impl Responder {
|
||||
let mut conn = match pool.get() {
|
||||
Ok(conn) => conn,
|
||||
Err(_) => return HttpResponse::InternalServerError().finish(),
|
||||
};
|
||||
match T::delete(&mut conn, id.into_inner()) {
|
||||
Ok(_) => HttpResponse::NoContent().finish(),
|
||||
Err(diesel::result::Error::NotFound) => HttpResponse::NotFound().finish(),
|
||||
Err(_) => HttpResponse::InternalServerError().finish(),
|
||||
}
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
pub mod r#trait;
|
||||
pub mod handlers;
|
@ -1,14 +0,0 @@
|
||||
use diesel::prelude::*;
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
|
||||
pub trait CrudEntity: Sized + Serialize {
|
||||
type Id: Serialize + DeserializeOwned + 'static;
|
||||
type CreateInput: DeserializeOwned + 'static;
|
||||
type UpdateInput: DeserializeOwned + 'static;
|
||||
|
||||
fn find_all(conn: &mut PgConnection, limit: Option<i64>, offset: Option<i64>) -> Result<Vec<Self>, diesel::result::Error>;
|
||||
fn find_by_id(conn: &mut PgConnection, id: Self::Id) -> Result<Self, diesel::result::Error>;
|
||||
fn insert(conn: &mut PgConnection, item: Self::CreateInput) -> Result<Self, diesel::result::Error>;
|
||||
fn update(conn: &mut PgConnection, id: Self::Id, item: Self::UpdateInput) -> Result<Self, diesel::result::Error>;
|
||||
fn delete(conn: &mut PgConnection, id: Self::Id) -> Result<usize, diesel::result::Error>;
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::r2d2::{self, ConnectionManager};
|
||||
use std::env;
|
||||
|
||||
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||
|
||||
pub fn establish_connection_pool() -> Pool {
|
||||
dotenv::dotenv().ok();
|
||||
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||
let manager = ConnectionManager::<PgConnection>::new(database_url);
|
||||
r2d2::Pool::builder()
|
||||
.build(manager)
|
||||
.expect("Failed to create pool")
|
||||
}
|
@ -1 +0,0 @@
|
||||
pub mod connection;
|
40
src/main.rs
40
src/main.rs
@ -1,24 +1,24 @@
|
||||
use actix_web::{web, App, HttpServer};
|
||||
use db::connection::establish_connection_pool;
|
||||
use models::user::User;
|
||||
use routes::crud::add_crud_routes;
|
||||
use crate::config::parameter::AppConfig;
|
||||
|
||||
mod crud;
|
||||
mod models;
|
||||
mod db;
|
||||
mod routes;
|
||||
mod schema;
|
||||
mod config;
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let pool = establish_connection_pool();
|
||||
|
||||
HttpServer::new(move || {
|
||||
let mut app = App::new().app_data(web::Data::new(pool.clone()));
|
||||
app = add_crud_routes::<User>(app, "/users");
|
||||
app
|
||||
fn main() {
|
||||
let config = AppConfig::new()
|
||||
.map_err(|e| {
|
||||
eprintln!("Configuration error: {}", e);
|
||||
std::process::exit(1);
|
||||
})
|
||||
.bind("0.0.0.0:3000")?
|
||||
.run()
|
||||
.await
|
||||
.and_then(|cfg| {
|
||||
cfg.validate().map_err(|errors| {
|
||||
eprintln!(
|
||||
"Configuration validation errors:\n\t{}",
|
||||
errors.join("\n\t")
|
||||
);
|
||||
std::process::exit(1);
|
||||
})?;
|
||||
Ok(cfg)
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
println!("Hello, world! {}", config.service_version);
|
||||
}
|
||||
|
@ -1 +0,0 @@
|
||||
pub mod user;
|
@ -1,63 +0,0 @@
|
||||
use diesel::prelude::*;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use crate::{crud::r#trait::CrudEntity, schema::users};
|
||||
|
||||
#[derive(Serialize, Deserialize, Queryable, Insertable)]
|
||||
#[diesel(table_name = users)]
|
||||
pub struct User {
|
||||
id: i32,
|
||||
name: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Insertable)]
|
||||
#[diesel(table_name = users)]
|
||||
pub struct NewUser {
|
||||
name: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, AsChangeset)]
|
||||
#[diesel(table_name = users)]
|
||||
pub struct UpdateUser {
|
||||
name: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
impl CrudEntity for User {
|
||||
type Id = i32;
|
||||
type CreateInput = NewUser;
|
||||
type UpdateInput = UpdateUser; // Changed from User to UpdateUser
|
||||
|
||||
fn find_all(conn: &mut PgConnection, limit: Option<i64>, offset: Option<i64>) -> Result<Vec<Self>, diesel::result::Error> {
|
||||
use crate::schema::users::dsl::*;
|
||||
let mut query = users.into_boxed();
|
||||
if let Some(l) = limit {
|
||||
query = query.limit(l);
|
||||
}
|
||||
if let Some(o) = offset {
|
||||
query = query.offset(o);
|
||||
}
|
||||
query.load::<Self>(conn)
|
||||
}
|
||||
|
||||
fn find_by_id(conn: &mut PgConnection, id: Self::Id) -> Result<Self, diesel::result::Error> {
|
||||
use crate::schema::users::dsl::*;
|
||||
users.filter(id.eq(id)).first::<Self>(conn)
|
||||
}
|
||||
|
||||
fn insert(conn: &mut PgConnection, item: Self::CreateInput) -> Result<Self, diesel::result::Error> {
|
||||
use crate::schema::users;
|
||||
diesel::insert_into(users::table).values(&item).get_result(conn)
|
||||
}
|
||||
|
||||
fn update(conn: &mut PgConnection, id: Self::Id, item: Self::UpdateInput) -> Result<Self, diesel::result::Error> {
|
||||
use crate::schema::users::dsl::*;
|
||||
diesel::update(users.filter(id.eq(id))).set(&item).get_result(conn)
|
||||
}
|
||||
|
||||
fn delete(conn: &mut PgConnection, id: Self::Id) -> Result<usize, diesel::result::Error> {
|
||||
use crate::schema::users::dsl::*;
|
||||
diesel::delete(users.filter(id.eq(id))).execute(conn)
|
||||
}
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
use actix_web::{dev::{ServiceFactory, ServiceRequest}, web, App};
|
||||
use crate::crud::{handlers, r#trait::CrudEntity};
|
||||
|
||||
pub fn add_crud_routes<T: CrudEntity + 'static>(mut app: App<T>, path: &str) -> App<T>
|
||||
where
|
||||
T::Id: serde::de::DeserializeOwned + serde::Serialize + 'static,
|
||||
T::CreateInput: serde::de::DeserializeOwned + 'static,
|
||||
T::UpdateInput: serde::de::DeserializeOwned + 'static,
|
||||
|
||||
|
||||
T: ServiceFactory<ServiceRequest, Config = (), Error = actix_web::Error, InitError = ()>
|
||||
{
|
||||
app = app.service(
|
||||
web::resource(path)
|
||||
.route(web::get().to(handlers::get_all::<T>))
|
||||
.route(web::post().to(handlers::create::<T>)),
|
||||
);
|
||||
app.service(
|
||||
web::resource(&format!("{}/{{id}}", path))
|
||||
.route(web::get().to(handlers::get_one::<T>))
|
||||
.route(web::put().to(handlers::update::<T>))
|
||||
.route(web::delete().to(handlers::delete::<T>)),
|
||||
)
|
||||
}
|
@ -1 +0,0 @@
|
||||
pub mod crud;
|
@ -1,9 +0,0 @@
|
||||
// @generated automatically by Diesel CLI.
|
||||
|
||||
diesel::table! {
|
||||
users (id) {
|
||||
id -> Int4,
|
||||
name -> Varchar,
|
||||
email -> Varchar,
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user