Implement points with a postgresql database
This commit is contained in:
5
.gitignore
vendored
5
.gitignore
vendored
@ -1,3 +1,8 @@
|
||||
# my gitignore
|
||||
todo.md
|
||||
.env
|
||||
compose.yaml
|
||||
|
||||
# ---> Rust
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
|
||||
1270
Cargo.lock
generated
1270
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -5,5 +5,7 @@ edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
axum = "0.8.6"
|
||||
dotenvy = "0.15.7"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
sqlx = { version = "0.8.6", features = ["postgres", "runtime-tokio"] }
|
||||
tokio = { version = "1.48.0", features = ["full"] }
|
||||
|
||||
9
migrations/create_tables.sql
Normal file
9
migrations/create_tables.sql
Normal file
@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS games(
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
publishing_house TEXT NOT NULL,
|
||||
developer TEXT NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
multiplayer BOOLEAN NOT NULL,
|
||||
is_free_to_play BOOLEAN NOT NULL
|
||||
);
|
||||
164
src/main.rs
164
src/main.rs
@ -1,31 +1,163 @@
|
||||
use axum::{extract::Query, response::IntoResponse, routing::delete, routing::get, routing::post};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Query, State},
|
||||
response::IntoResponse,
|
||||
routing::{delete, get, post},
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
use std::fs;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
async fn games_list() -> impl IntoResponse {
|
||||
axum::http::StatusCode::NOT_IMPLEMENTED
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub pool: PgPool,
|
||||
}
|
||||
|
||||
async fn add_game() -> impl IntoResponse {
|
||||
axum::http::StatusCode::NOT_IMPLEMENTED
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize)]
|
||||
struct Game {
|
||||
id: i32,
|
||||
name: String,
|
||||
publishing_house: String,
|
||||
developer: String,
|
||||
description: String,
|
||||
multiplayer: bool,
|
||||
is_free_to_play: bool,
|
||||
//
|
||||
// release_date: i32, // date?
|
||||
// rating: Option<f32>, // enum?
|
||||
// cover_image_url: Option<String>,
|
||||
//
|
||||
// platforms: Vec<String>, // enum
|
||||
// genre: Vec<String>, // enum?
|
||||
// age_rating: Option<String>, // enum?
|
||||
// game_engine: Option<String>, // enum?
|
||||
// tags: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
async fn insert_game() -> impl IntoResponse {
|
||||
axum::http::StatusCode::NOT_IMPLEMENTED
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize)]
|
||||
struct CreateGame {
|
||||
name: String,
|
||||
publishing_house: String,
|
||||
developer: String,
|
||||
description: String,
|
||||
multiplayer: bool,
|
||||
is_free_to_play: bool,
|
||||
}
|
||||
|
||||
async fn delete_game() -> impl IntoResponse {
|
||||
axum::http::StatusCode::NOT_IMPLEMENTED
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct GetGameQuery {
|
||||
pub id: Option<i32>,
|
||||
}
|
||||
|
||||
fn database_url() -> String {
|
||||
let _ = dotenvy::dotenv();
|
||||
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL should be set");
|
||||
println!("DATABASE_URL={database_url}");
|
||||
database_url
|
||||
}
|
||||
|
||||
async fn create_table(pool: &PgPool) {
|
||||
let sql_up =
|
||||
fs::read_to_string("migrations/create_tables.sql").expect("Failed to read SQL file");
|
||||
|
||||
sqlx::query(&sql_up)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("Could not create database tables");
|
||||
}
|
||||
|
||||
fn router(state: AppState) -> axum::Router {
|
||||
axum::Router::new()
|
||||
.route("/api/games", get(games_list).post(add_game))
|
||||
.route("/api/games/{id}", post(insert_game).delete(delete_game))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let router = axum::Router::new()
|
||||
.route("/api/games", get(games_list))
|
||||
.route("/api/games", post(add_game))
|
||||
.route("/api/games/{id}", post(insert_game))
|
||||
.route("/api/games/{id}", delete(delete_game));
|
||||
let state = AppState {
|
||||
pool: PgPool::connect(&database_url())
|
||||
.await
|
||||
.expect("Could not connect to database"),
|
||||
};
|
||||
|
||||
create_table(&state.pool);
|
||||
|
||||
let addr = "127.0.0.1:8000";
|
||||
let listener = TcpListener::bind(addr).await.unwrap();
|
||||
println!("listening at {addr}");
|
||||
axum::serve(listener, router).await.unwrap();
|
||||
println!("Listening at {addr}");
|
||||
axum::serve(listener, router(state)).await.unwrap();
|
||||
}
|
||||
|
||||
async fn games_list(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<GetGameQuery>,
|
||||
) -> impl IntoResponse {
|
||||
let games: Vec<Game> = sqlx::query_as!(Game, "SELECT * FROM games")
|
||||
.fetch_all(&state.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
Json(games)
|
||||
}
|
||||
|
||||
async fn add_game(
|
||||
State(state): State<AppState>,
|
||||
Json(game): Json<CreateGame>,
|
||||
) -> impl IntoResponse {
|
||||
let result = sqlx::query!(
|
||||
"INSERT INTO games (name, publishing_house, developer, description, multiplayer, is_free_to_play)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
game.name,
|
||||
game.publishing_house,
|
||||
game.developer,
|
||||
game.description,
|
||||
game.multiplayer,
|
||||
game.is_free_to_play,
|
||||
)
|
||||
.execute(&state.pool)
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(_) => axum::http::StatusCode::CREATED,
|
||||
Err(_) => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
async fn insert_game(
|
||||
State(state): State<AppState>,
|
||||
Json(game): Json<CreateGame>,
|
||||
) -> impl IntoResponse {
|
||||
sqlx::query!(
|
||||
"INSERT INTO games(name, publishing_house, developer, description, multiplayer, is_free_to_play) VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
game.name,
|
||||
game.publishing_house,
|
||||
game.developer,
|
||||
game.description,
|
||||
game.multiplayer,
|
||||
game.is_free_to_play,
|
||||
)
|
||||
.execute(&state.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
axum::http::StatusCode::OK
|
||||
}
|
||||
|
||||
async fn delete_game(
|
||||
State(state): State<AppState>,
|
||||
Query(query): Query<GetGameQuery>,
|
||||
) -> impl IntoResponse {
|
||||
if let Some(id) = query.id {
|
||||
let result = sqlx::query!("DELETE FROM games WHERE id = $1", id)
|
||||
.execute(&state.pool)
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(_) => axum::http::StatusCode::OK,
|
||||
Err(_) => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
} else {
|
||||
axum::http::StatusCode::BAD_REQUEST
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user