···11+**Pour lancer**
22+33+```bash
44+docker compose up -d # lance le container de la db
55+sqlx database create # cree la DB "dyfc" si elle n'existe pas
66+sqlx migrate run # applique les migrations
77+cargo run # depuis /backend
88+```
99+1010+`Le sqlx::migrate!()` dans le main.rs creera la table games automatiquement au premier
1111+demarrage.
1212+1313+**Commandes utiles**
1414+```bash
1515+docker compose logs db # voir les logs Postgres
1616+docker compose down # arreter (les donnees restent dans le volume)
1717+docker compose down -v # arreter ET supprimer les donnees (reset complet)
1818+```
···11+[package]
22+name = "backend"
33+version = "0.1.0"
44+edition = "2024"
55+66+[dependencies]
77+anyhow = "1.0.102"
88+axum = "0.8.9"
99+dotenvy = "0.15.7"
1010+serde = { version = "1.0.228", features = ["derive"] }
1111+serde_json = "1.0.149"
1212+sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "json"] }
1313+tokio = { version = "1.52.1", features = ["full"] }
1414+tower-http = { version = "0.6.8", features = ["cors", "trace"] }
1515+tracing = "0.1.44"
1616+tracing-subscriber = {version = "0.3.23", features = ["env-filter"] }
+6
backend/migrations/001_create_games.sql
···11+CREATE TABLE IF NOT EXISTS games (
22+ id SERIAL PRIMARY KEY,
33+ state JSONB NOT NULL,
44+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
55+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
66+);
+156
backend/src/main.rs
···11+use axum::{
22+ Json, Router,
33+ extract::{Path, State},
44+ http::StatusCode,
55+ response::IntoResponse,
66+ routing::{get, post},
77+};
88+use serde::{Deserialize, Serialize};
99+use sqlx::PgPool;
1010+use tower_http::cors::CorsLayer;
1111+use tower_http::trace::TraceLayer;
1212+use tracing_subscriber;
1313+1414+// === App State ===
1515+// Ce qui est partage entre tous les handlers (clone-able, passe via State)
1616+1717+#[derive(Clone)]
1818+struct AppState {
1919+ db: PgPool,
2020+}
2121+2222+// === Models ===
2323+// Pour l'instant un GameState minimal — on le fera grandir plus tard
2424+2525+#[derive(Debug, Clone, Serialize, Deserialize)]
2626+struct GameState {
2727+ turn: u32,
2828+ phase: String, // deviendra un enum plus tard
2929+ resources: Resources,
3030+}
3131+3232+#[derive(Debug, Clone, Serialize, Deserialize)]
3333+struct Resources {
3434+ gold: i32,
3535+ food: i32,
3636+ population: i32,
3737+}
3838+3939+impl GameState {
4040+ fn new() -> Self {
4141+ Self {
4242+ turn: 1,
4343+ phase: "draw".to_string(),
4444+ resources: Resources {
4545+ gold: 100,
4646+ food: 50,
4747+ population: 10,
4848+ },
4949+ }
5050+ }
5151+}
5252+5353+// === Errors ===
5454+// Un type d'erreur applicatif simple avec anyhow en interne
5555+5656+enum AppError {
5757+ NotFound(String),
5858+ Internal(anyhow::Error),
5959+}
6060+6161+// Convertit nos erreurs en reponses HTTP automatiquement
6262+impl IntoResponse for AppError {
6363+ fn into_response(self) -> axum::response::Response {
6464+ let (status, message) = match self {
6565+ AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
6666+ AppError::Internal(err) => (
6767+ StatusCode::INTERNAL_SERVER_ERROR,
6868+ format!("Internal error: {err}"),
6969+ ),
7070+ };
7171+ (status, Json(serde_json::json!({ "error": message }))).into_response()
7272+ }
7373+}
7474+7575+// Permet d'utiliser `?` sur les erreurs sqlx/anyhow dans les handlers
7676+impl From<sqlx::Error> for AppError {
7777+ fn from(err: sqlx::Error) -> Self {
7878+ AppError::Internal(err.into())
7979+ }
8080+}
8181+8282+// === Handlers ===
8383+8484+async fn health() -> &'static str {
8585+ "ok"
8686+}
8787+8888+async fn create_game(State(state): State<AppState>) -> Result<Json<serde_json::Value>, AppError> {
8989+ let game = GameState::new();
9090+ let game_json = serde_json::to_value(&game).unwrap();
9191+9292+ let row = sqlx::query_scalar!(
9393+ r#"INSERT INTO games (state) VALUES ($1) RETURNING id"#,
9494+ game_json
9595+ )
9696+ .fetch_one(&state.db)
9797+ .await?;
9898+9999+ Ok(Json(serde_json::json!({
100100+ "id": row,
101101+ "state": game
102102+ })))
103103+}
104104+105105+async fn get_game(
106106+ Path(id): Path<i32>,
107107+ State(state): State<AppState>,
108108+) -> Result<Json<serde_json::Value>, AppError> {
109109+ let row = sqlx::query!(r#"SELECT id, state FROM games WHERE id = $1"#, id)
110110+ .fetch_optional(&state.db)
111111+ .await?
112112+ .ok_or_else(|| AppError::NotFound(format!("Game {id} not found")))?;
113113+114114+ Ok(Json(serde_json::json!({
115115+ "id": row.id,
116116+ "state": row.state
117117+ })))
118118+}
119119+120120+// === Main ===
121121+122122+#[tokio::main]
123123+async fn main() -> anyhow::Result<()> {
124124+ // Charge le .env (DATABASE_URL, etc.)
125125+ dotenvy::dotenv().ok();
126126+127127+ // Initialise le logging en lisant RUST_LOG (ex: tower_http=debug,backend=debug)
128128+ tracing_subscriber::fmt()
129129+ .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
130130+ .init();
131131+132132+ // Connexion a PostgreSQL
133133+ let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
134134+ let pool = PgPool::connect(&database_url).await?;
135135+136136+ // Lance les migrations SQL au demarrage
137137+ sqlx::migrate!().run(&pool).await?;
138138+139139+ let state = AppState { db: pool };
140140+141141+ // Routes
142142+ let app = Router::new()
143143+ .route("/health", get(health))
144144+ .route("/games", post(create_game))
145145+ .route("/games/{id}", get(get_game))
146146+ .layer(CorsLayer::permissive()) // autorise tout en dev
147147+ .layer(TraceLayer::new_for_http())
148148+ .with_state(state);
149149+150150+ let addr = "0.0.0.0:3000";
151151+ tracing::info!("Listening on {addr}");
152152+ let listener = tokio::net::TcpListener::bind(addr).await?;
153153+ axum::serve(listener, app).await?;
154154+155155+ Ok(())
156156+}
···11+# Svelte + TS + Vite
22+33+This template should help get you started developing with Svelte and TypeScript in Vite.
44+55+## Recommended IDE Setup
66+77+[VS Code](https://code.visualstudio.com/) + [Svelte](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode).
88+99+## Need an official Svelte framework?
1010+1111+Check out [SvelteKit](https://github.com/sveltejs/kit#readme), which is also powered by Vite. Deploy anywhere with its serverless-first approach and adapt to various platforms, with out of the box support for TypeScript, SCSS, and Less, and easily-added support for mdsvex, GraphQL, PostCSS, Tailwind CSS, and more.
1212+1313+## Technical considerations
1414+1515+**Why use this over SvelteKit?**
1616+1717+- It brings its own routing solution which might not be preferable for some users.
1818+- It is first and foremost a framework that just happens to use Vite under the hood, not a Vite app.
1919+2020+This template contains as little as possible to get started with Vite + TypeScript + Svelte, while taking into account the developer experience with regards to HMR and intellisense. It demonstrates capabilities on par with the other `create-vite` templates and is a good starting point for beginners dipping their toes into a Vite + Svelte project.
2121+2222+Should you later need the extended capabilities and extensibility provided by SvelteKit, the template has been structured similarly to SvelteKit so that it is easy to migrate.
2323+2424+**Why `global.d.ts` instead of `compilerOptions.types` inside `jsconfig.json` or `tsconfig.json`?**
2525+2626+Setting `compilerOptions.types` shuts out all other types not explicitly listed in the configuration. Using triple-slash references keeps the default TypeScript setting of accepting type information from the entire workspace, while also adding `svelte` and `vite/client` type information.
2727+2828+**Why include `.vscode/extensions.json`?**
2929+3030+Other templates indirectly recommend extensions via the README, but this file allows VS Code to prompt the user to install the recommended extension upon opening the project.
3131+3232+**Why enable `allowJs` in the TS template?**
3333+3434+While `allowJs: false` would indeed prevent the use of `.js` files in the project, it does not prevent the use of JavaScript syntax in `.svelte` files. In addition, it would force `checkJs: false`, bringing the worst of both worlds: not being able to guarantee the entire codebase is TypeScript, and also having worse typechecking for the existing JavaScript. In addition, there are valid use cases in which a mixed codebase may be relevant.
3535+3636+**Why is HMR not preserving my local component state?**
3737+3838+HMR state preservation comes with a number of gotchas! It has been disabled by default in both `svelte-hmr` and `@sveltejs/vite-plugin-svelte` due to its often surprising behavior. You can read the details [here](https://github.com/rixo/svelte-hmr#svelte-hmr).
3939+4040+If you have state that's important to retain within a component, consider creating an external store which would not be replaced by HMR.
4141+4242+```ts
4343+// store.ts
4444+// An extremely simple external store
4545+import { writable } from 'svelte/store'
4646+export default writable(0)
4747+```