feat: bootstrap fullstack NX monorepo (Spring Boot + React)

- Add Spring Boot 3.4 backend with health API, CORS, and dev/prod profiles
- Add React 18 + Vite frontend with typed health client
- Configure NX workspace, pnpm, and Docker Compose stacks
- Document stack, commands, and layout in README
- Add .gitignore for Node, Java, Docker, and IDE artifacts
This commit is contained in:
Camille 2026-05-29 23:42:03 +02:00
parent 91a659a938
commit 7a9383e87f
39 changed files with 10382 additions and 1 deletions

16
.env.example Normal file
View file

@ -0,0 +1,16 @@
# ──────────────────────────────────────────
# CityGame — Environment Variables
# Copy this file to .env and fill in values
# ──────────────────────────────────────────
# === Database ===
DB_NAME=citygame
DB_USERNAME=citygame
DB_PASSWORD=citygame_change_me_in_prod
# === Backend ===
BACKEND_PORT=8080
CORS_ALLOWED_ORIGINS=http://localhost
# === Frontend ===
FRONTEND_PORT=80

99
.gitignore vendored Normal file
View file

@ -0,0 +1,99 @@
# ──────────────────────────────────────────
# Node / NX
# ──────────────────────────────────────────
node_modules/
dist/
.nx/cache
.nx/workspace-data
.nx/installation
*.local
# Lockfiles — seul pnpm-lock.yaml est versionné
package-lock.json
yarn.lock
# pnpm
pnpm-debug.log*
.pnpm-store/
# ──────────────────────────────────────────
# Java / Maven
# ──────────────────────────────────────────
apps/backend/target/
**/*.class
*.jar
*.war
*.ear
hs_err_pid*
replay_pid*
# Maven wrapper cache
.m2/
# ──────────────────────────────────────────
# Environment
# ──────────────────────────────────────────
.env
.env.local
.env.*.local
# ──────────────────────────────────────────
# IDE — IntelliJ IDEA
# ──────────────────────────────────────────
.idea/
*.iml
*.ipr
*.iws
out/
# IDE — VS Code (keep workspace-shared settings)
.vscode/settings.json
.vscode/*.code-workspace
.vscode/.ropeproject
# IDE — Eclipse
.classpath
.project
.settings/
bin/
# ──────────────────────────────────────────
# OS
# ──────────────────────────────────────────
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
desktop.ini
# ──────────────────────────────────────────
# Docker
# ──────────────────────────────────────────
.docker/
# ──────────────────────────────────────────
# Tests & Coverage
# ──────────────────────────────────────────
coverage/
apps/backend/target/surefire-reports/
# ──────────────────────────────────────────
# Logs
# ──────────────────────────────────────────
*.log
logs/
apps/backend/logs/
# ──────────────────────────────────────────
# Temporaires
# ──────────────────────────────────────────
tmp/
temp/
*.tmp
*.bak
*.swp
*.swo
*~

10
.npmrc Normal file
View file

@ -0,0 +1,10 @@
# pnpm configuration
# Allow build scripts for trusted packages (NX, esbuild)
enable-pre-post-scripts=true
# Exact versions pour la reproductibilité
save-exact=true
# Hoist les deps NX pour que les executors soient trouvés
public-hoist-pattern[]=*nx*
public-hoist-pattern[]=*@nx*

187
README.md
View file

@ -1 +1,186 @@
# Test project # 🏙️ CityGame — Fullstack Template
> **NX Monorepo** · Spring Boot 3 · React 18 · TypeScript · Vite · Docker Compose
---
## Stack
| Layer | Technology |
|---|---|
| **Backend** | Spring Boot 3.4, Java 21, Maven, Lombok, JPA, Actuator |
| **Frontend** | React 18, TypeScript, Vite 5, Vitest |
| **Database** | H2 (dev) / PostgreSQL 16 (prod) |
| **Infra** | Docker Compose, nginx, multi-stage builds |
| **Monorepo** | NX 21 — caching, task graph, affected builds |
---
## Quickstart
### Prérequis
- Node.js ≥ 20
- pnpm ≥ 10 (`npm install -g pnpm` ou `corepack enable`)
- Java 21
- Docker + Docker Compose
### Installation
```bash
git clone <repo-url> citygame
cd citygame
pnpm install
```
---
## Commandes
### 🔥 Mode Développement (hot reload)
```bash
# Lance frontend (Vite HMR :5173) + backend (Spring DevTools :8080) en parallèle
pnpm dev
# Ou individuellement :
pnpm dev:frontend # Vite dev server → http://localhost:5173
pnpm dev:backend # Spring Boot → http://localhost:8080
```
> Le backend utilise H2 en mémoire en mode dev. Pas besoin de Docker.
> Pour utiliser PostgreSQL en dev : `docker compose -f docker-compose.dev.yml up -d`
### 🏗️ Build
```bash
# Build tout (frontend Vite + backend Maven JAR)
pnpm build
# Build individuellement :
pnpm build:frontend # → dist/apps/frontend/
pnpm build:backend # → apps/backend/target/*.jar
# Build les images Docker
pnpm docker:build
pnpm docker:build:frontend
pnpm docker:build:backend
```
### 🚀 Production (Docker Compose)
```bash
# Copier et configurer les variables d'environnement
cp .env.example .env
# Démarrer la stack prod (après docker:build)
pnpm start # docker compose up (foreground)
pnpm start:detach # docker compose up -d (background)
pnpm stop # docker compose down
pnpm logs # docker compose logs -f
```
### 🧪 Tests
```bash
pnpm test # Tous les tests
pnpm test:frontend # Vitest
pnpm test:backend # Maven Surefire (JUnit 5)
```
### 📊 NX Tools
```bash
npx nx graph # Visualise le graphe de dépendances
npx nx affected -t test # Tests des projets affectés par les changements
npx nx affected -t build # Build uniquement ce qui a changé
npx nx reset # Nettoie le cache NX
```
---
## Structure
```
CityGame/
├── apps/
│ ├── backend/ # Spring Boot (Maven)
│ │ ├── src/main/java/com/citygame/
│ │ │ ├── CityGameApplication.java
│ │ │ ├── api/HealthController.java
│ │ │ └── config/CorsConfig.java
│ │ ├── src/main/resources/
│ │ │ ├── application.yml # Base config
│ │ │ ├── application-dev.yml # H2 + DevTools
│ │ │ └── application-prod.yml # PostgreSQL
│ │ ├── pom.xml
│ │ ├── project.json # NX targets
│ │ └── Dockerfile # Multi-stage
│ │
│ └── frontend/ # Vite + React + TypeScript
│ ├── src/
│ │ ├── api/health.ts # Client API typé
│ │ ├── App.tsx
│ │ └── main.tsx
│ ├── vite.config.ts # Proxy /api → backend
│ ├── project.json # NX targets
│ └── Dockerfile # Multi-stage (nginx)
├── docker-compose.yml # Prod stack
├── docker-compose.dev.yml # Dev (DB seulement)
├── nx.json # Config NX + caching
├── package.json # Scripts & workspace
└── .env.example # Variables template
```
---
## API Endpoints
| Méthode | URL | Description |
|---|---|---|
| `GET` | `/api/hello` | Demo endpoint (message + timestamp) |
| `GET` | `/actuator/health` | Health check Spring Boot |
| `GET` | `/actuator/info` | Infos application |
| `GET` | `/h2-console` | Console H2 (dev seulement) |
---
## Ajouter une fonctionnalité
### Nouveau endpoint backend
1. Créer un controller dans `apps/backend/src/main/java/com/citygame/api/`
2. Redémarrage automatique via Spring DevTools
### Nouveau composant frontend
1. Créer dans `apps/backend/src/`
2. HMR Vite — mise à jour sans rechargement
### Nouvelle app dans le monorepo
```bash
# Nouvelle app React
npx nx g @nx/react:app apps/my-new-app --bundler=vite
# Nouvelle lib partagée TypeScript
npx nx g @nx/js:lib libs/shared-types
```
---
## Configuration Docker (prod)
Copier `.env.example``.env` et configurer :
```env
DB_PASSWORD=un_mot_de_passe_fort
CORS_ALLOWED_ORIGINS=https://votredomaine.com
```
---
## License
MIT

View file

@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip

48
apps/backend/Dockerfile Normal file
View file

@ -0,0 +1,48 @@
# Stage 1: Build with Maven
FROM maven:3.9-eclipse-temurin-21-alpine AS builder
WORKDIR /build
# Copy pom.xml first for dependency caching
COPY pom.xml .
# Download dependencies (cached layer)
RUN mvn dependency:go-offline -q
# Copy source code
COPY src ./src
# Build the application (layered JAR)
RUN mvn package -DskipTests -q
# Extract layers for optimal caching
RUN mkdir -p target/dependency && \
cd target/dependency && \
java -Djarmode=layertools -jar ../*.jar extract
# Stage 2: Runtime — minimal JRE
FROM eclipse-temurin:21-jre-alpine AS runner
# Security: run as non-root
RUN addgroup -S citygame && adduser -S citygame -G citygame
WORKDIR /app
# Copy layered JAR (order: dependencies first for max cache hits)
COPY --from=builder --chown=citygame:citygame /build/target/dependency/dependencies/ ./
COPY --from=builder --chown=citygame:citygame /build/target/dependency/spring-boot-loader/ ./
COPY --from=builder --chown=citygame:citygame /build/target/dependency/snapshot-dependencies/ ./
COPY --from=builder --chown=citygame:citygame /build/target/dependency/application/ ./
USER citygame
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
CMD wget -qO- http://localhost:8080/actuator/health || exit 1
ENTRYPOINT ["java", \
"-XX:+UseContainerSupport", \
"-XX:MaxRAMPercentage=75.0", \
"-Djava.security.egd=file:/dev/./urandom", \
"org.springframework.boot.loader.launch.JarLauncher"]

295
apps/backend/mvnw vendored Executable file
View file

@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

189
apps/backend/mvnw.cmd vendored Normal file
View file

@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

111
apps/backend/pom.xml Normal file
View file

@ -0,0 +1,111 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.5</version>
<relativePath/>
</parent>
<groupId>com.citygame</groupId>
<artifactId>backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>backend</name>
<description>CityGame Backend — Spring Boot REST API</description>
<properties>
<java.version>21</java.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA / Database -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Actuator (health, metrics) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- DevTools (hot reload) — dev only -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- H2 (in-memory DB for dev) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- PostgreSQL (prod) -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Tests -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
<!-- Layered JAR for optimal Docker caching -->
<layers>
<enabled>true</enabled>
</layers>
</configuration>
</plugin>
</plugins>
</build>
</project>

57
apps/backend/project.json Normal file
View file

@ -0,0 +1,57 @@
{
"name": "backend",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/backend/src",
"projectType": "application",
"tags": ["scope:backend", "type:app"],
"targets": {
"serve": {
"executor": "nx:run-commands",
"options": {
"command": "./mvnw spring-boot:run -Dspring-boot.run.profiles=dev -Dspring-boot.run.jvmArguments=\"-Xmx512m\"",
"cwd": "{projectRoot}"
}
},
"build": {
"executor": "nx:run-commands",
"cache": true,
"inputs": [
"{projectRoot}/src/**/*",
"{projectRoot}/pom.xml"
],
"outputs": ["{projectRoot}/target"],
"options": {
"command": "./mvnw package -DskipTests -q",
"cwd": "{projectRoot}"
}
},
"test": {
"executor": "nx:run-commands",
"cache": true,
"inputs": [
"{projectRoot}/src/**/*",
"{projectRoot}/pom.xml"
],
"outputs": ["{projectRoot}/target/surefire-reports"],
"options": {
"command": "./mvnw test",
"cwd": "{projectRoot}"
}
},
"lint": {
"executor": "nx:run-commands",
"options": {
"command": "./mvnw checkstyle:check",
"cwd": "{projectRoot}"
}
},
"docker-build": {
"executor": "nx:run-commands",
"dependsOn": ["build"],
"options": {
"command": "docker build -t citygame-backend -f apps/backend/Dockerfile .",
"cwd": "{workspaceRoot}"
}
}
}
}

View file

@ -0,0 +1,12 @@
package com.citygame;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CityGameApplication {
public static void main(String[] args) {
SpringApplication.run(CityGameApplication.class, args);
}
}

View file

@ -0,0 +1,23 @@
package com.citygame.api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
@RestController
@RequestMapping("/api")
public class HealthController {
@GetMapping("/hello")
public HelloResponse hello() {
return new HelloResponse(
"Hello from Spring Boot! 🚀",
"UP",
Instant.now().toString()
);
}
public record HelloResponse(String message, String status, String timestamp) {}
}

View file

@ -0,0 +1,23 @@
package com.citygame.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Value("${citygame.cors.allowed-origins:http://localhost:5173}")
private String[] allowedOrigins;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins(allowedOrigins)
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}

View file

@ -0,0 +1,40 @@
# ──────────────────────────────────────────────
# DEV profile — H2 in-memory, DevTools enabled
# Active: spring.profiles.active=dev
# ──────────────────────────────────────────────
spring:
devtools:
restart:
enabled: true
additional-paths: src/main/java
livereload:
enabled: true
datasource:
url: jdbc:h2:mem:citygamedb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
driver-class-name: org.h2.Driver
username: sa
password: ""
h2:
console:
enabled: true
path: /h2-console
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create-drop
show-sql: true
server:
port: 8080
logging:
level:
com.citygame: DEBUG
org.springframework.web: DEBUG
citygame:
cors:
allowed-origins: http://localhost:5173

View file

@ -0,0 +1,41 @@
# ──────────────────────────────────────────────
# PROD profile — PostgreSQL, no DevTools
# Env vars required: DB_URL, DB_USERNAME, DB_PASSWORD
# ──────────────────────────────────────────────
spring:
devtools:
restart:
enabled: false
datasource:
url: ${DB_URL:jdbc:postgresql://db:5432/citygame}
username: ${DB_USERNAME:citygame}
password: ${DB_PASSWORD:citygame}
hikari:
maximum-pool-size: 10
minimum-idle: 2
connection-timeout: 20000
idle-timeout: 300000
jpa:
database-platform: org.hibernate.dialect.PostgreSQLDialect
hibernate:
ddl-auto: validate
show-sql: false
server:
port: 8080
logging:
level:
com.citygame: INFO
root: WARN
management:
endpoint:
health:
show-details: never
citygame:
cors:
allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost}

View file

@ -0,0 +1,28 @@
# ──────────────────────────────────────────────
# Base configuration (shared across profiles)
# ──────────────────────────────────────────────
spring:
application:
name: citygame-backend
# JPA base config
jpa:
open-in-view: false
properties:
hibernate:
format_sql: false
# Actuator
management:
endpoints:
web:
exposure:
include: health,info,metrics
endpoint:
health:
show-details: when-authorized
# App config
citygame:
cors:
allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:5173}

View file

@ -0,0 +1,25 @@
package com.citygame.api;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@WebMvcTest(HealthController.class)
class HealthControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void hello_shouldReturnUpStatus() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("UP"))
.andExpect(jsonPath("$.message").isNotEmpty())
.andExpect(jsonPath("$.timestamp").isNotEmpty());
}
}

38
apps/frontend/Dockerfile Normal file
View file

@ -0,0 +1,38 @@
# Stage 1: Build
FROM node:20-alpine AS builder
# Enable pnpm via corepack
RUN corepack enable && corepack prepare pnpm@latest --activate
WORKDIR /workspace
# Copy workspace manifests first for dependency caching
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml nx.json tsconfig.base.json ./
# Copy frontend app files
COPY apps/frontend ./apps/frontend
# Install all dependencies (frozen for reproducibility)
RUN pnpm install --frozen-lockfile
# Build the frontend
RUN pnpm nx run frontend:build --configuration=production
# Stage 2: Serve with nginx
FROM nginx:1.27-alpine AS runner
# Copy built assets
COPY --from=builder /workspace/dist/apps/frontend /usr/share/nginx/html
# Copy nginx config
COPY apps/frontend/nginx.conf /etc/nginx/conf.d/default.conf
# Create non-root user
RUN addgroup -S citygame && adduser -S citygame -G citygame
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget -qO- http://localhost:80/healthz || exit 1
CMD ["nginx", "-g", "daemon off;"]

14
apps/frontend/index.html Normal file
View file

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="CityGame — Fullstack template with Spring Boot, React, TypeScript and NX monorepo" />
<title>CityGame — Fullstack Template</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

40
apps/frontend/nginx.conf Normal file
View file

@ -0,0 +1,40 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss image/svg+xml;
# Health check endpoint
location /healthz {
access_log off;
return 200 "OK";
add_header Content-Type text/plain;
}
# Proxy API calls to the backend
location /api/ {
proxy_pass http://backend:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 60s;
}
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# SPA: redirect all routes to index.html
location / {
try_files $uri $uri/ /index.html;
}
}

View file

@ -0,0 +1,29 @@
{
"name": "frontend",
"version": "0.0.1",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"react": "^18.3.0",
"react-dom": "^18.3.0"
},
"devDependencies": {
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.0",
"typescript": "^5.5.0",
"vite": "^5.3.0",
"vitest": "^2.0.0",
"@vitest/ui": "^2.0.0",
"jsdom": "^24.0.0",
"@testing-library/react": "^16.0.0",
"@testing-library/jest-dom": "^6.0.0"
}
}

View file

@ -0,0 +1,61 @@
{
"name": "frontend",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/frontend/src",
"projectType": "application",
"tags": ["scope:frontend", "type:app"],
"targets": {
"serve": {
"executor": "@nx/vite:dev-server",
"defaultConfiguration": "development",
"options": {
"buildTarget": "frontend:build"
},
"configurations": {
"development": {
"buildTarget": "frontend:build:development",
"hmr": true
},
"production": {
"buildTarget": "frontend:build:production",
"hmr": false
}
}
},
"build": {
"executor": "@nx/vite:build",
"outputs": ["{options.outputPath}"],
"defaultConfiguration": "production",
"options": {
"outputPath": "dist/apps/frontend"
},
"configurations": {
"development": {
"mode": "development"
},
"production": {
"mode": "production"
}
}
},
"test": {
"executor": "@nx/vite:test",
"outputs": ["{workspaceRoot}/coverage/apps/frontend"],
"options": {
"passWithNoTests": true,
"reportsDirectory": "../../coverage/apps/frontend"
}
},
"lint": {
"executor": "@nx/eslint:lint"
},
"docker-build": {
"executor": "nx:run-commands",
"dependsOn": ["build"],
"options": {
"command": "docker build -t citygame-frontend -f apps/frontend/Dockerfile .",
"cwd": "{workspaceRoot}"
}
}
}
}

251
apps/frontend/src/App.css Normal file
View file

@ -0,0 +1,251 @@
.app {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
}
/* ── Hero ─────────────────────────────────────── */
.hero {
display: flex;
flex-direction: column;
align-items: center;
gap: 2rem;
max-width: 800px;
width: 100%;
text-align: center;
}
.hero-badge {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.4rem 1rem;
background: var(--bg-card);
border: 1px solid var(--border-strong);
border-radius: 999px;
font-size: 0.85rem;
font-weight: 600;
color: var(--text-secondary);
letter-spacing: 0.05em;
animation: fadeInDown 0.6s ease both;
}
.hero-title {
font-size: clamp(2.5rem, 6vw, 4.5rem);
font-weight: 800;
line-height: 1.1;
letter-spacing: -0.03em;
color: var(--text-primary);
animation: fadeInDown 0.6s 0.1s ease both;
}
.gradient-text {
background: var(--gradient-hero);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.hero-subtitle {
font-size: 1rem;
color: var(--text-secondary);
font-weight: 400;
letter-spacing: 0.04em;
animation: fadeInDown 0.6s 0.2s ease both;
}
/* ── API Card ─────────────────────────────────── */
.api-card {
width: 100%;
max-width: 500px;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.5rem;
backdrop-filter: blur(20px);
box-shadow: var(--shadow-card);
animation: fadeInUp 0.6s 0.3s ease both;
transition: border-color 0.3s ease, box-shadow 0.3s ease;
}
.api-card:hover {
border-color: var(--border-strong);
box-shadow: var(--shadow-glow), var(--shadow-card);
}
.api-card-header {
display: flex;
align-items: center;
gap: 0.6rem;
margin-bottom: 1rem;
}
.api-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--text-muted);
transition: background 0.3s ease;
flex-shrink: 0;
}
.api-dot[data-status="loading"] {
background: var(--accent-blue);
animation: pulse 1.2s ease-in-out infinite;
}
.api-dot[data-status="success"] {
background: var(--accent-green);
box-shadow: 0 0 8px var(--accent-green);
}
.api-dot[data-status="error"] {
background: var(--accent-red);
}
.api-label {
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--text-secondary);
}
.api-body {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
color: var(--text-secondary);
font-size: 0.9rem;
}
.api-body.success {
align-items: flex-start;
}
.api-body.error {
color: var(--accent-red);
}
.api-message {
font-size: 1.1rem;
font-weight: 600;
color: var(--text-primary);
}
.api-meta {
display: flex;
gap: 1.5rem;
font-size: 0.82rem;
color: var(--text-muted);
}
.api-meta strong {
color: var(--text-secondary);
}
.api-error-detail {
font-size: 0.8rem;
font-family: 'Courier New', monospace;
color: rgba(248, 113, 113, 0.7);
}
.api-hint {
font-size: 0.8rem;
color: var(--text-muted);
}
.api-hint code {
font-family: 'Courier New', monospace;
background: rgba(255, 255, 255, 0.07);
padding: 0.15em 0.4em;
border-radius: 4px;
font-size: 0.85em;
}
/* ── Spinner ──────────────────────────────────── */
.spinner {
width: 24px;
height: 24px;
border: 2px solid rgba(79, 142, 255, 0.2);
border-top-color: var(--accent-blue);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
/* ── Stack Grid ───────────────────────────────── */
.stack-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
width: 100%;
max-width: 500px;
animation: fadeInUp 0.6s 0.45s ease both;
}
@media (min-width: 600px) {
.stack-grid {
grid-template-columns: repeat(4, 1fr);
}
}
.stack-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.4rem;
padding: 1rem 0.75rem;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
cursor: default;
transition: all 0.2s ease;
}
.stack-card:hover {
background: var(--bg-card-hover);
border-color: var(--border-strong);
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
}
.stack-icon {
font-size: 1.4rem;
}
.stack-name {
font-size: 0.72rem;
font-weight: 600;
color: var(--text-secondary);
text-align: center;
}
.stack-port {
font-size: 0.68rem;
font-family: 'Courier New', monospace;
color: var(--accent-blue);
font-weight: 500;
}
/* ── Animations ───────────────────────────────── */
@keyframes fadeInDown {
from { opacity: 0; transform: translateY(-16px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeInUp {
from { opacity: 0; transform: translateY(16px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@keyframes pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(0.85); }
}

92
apps/frontend/src/App.tsx Normal file
View file

@ -0,0 +1,92 @@
import { useState, useEffect } from 'react';
import { fetchHealth, type HealthResponse } from './api/health';
import './App.css';
type Status = 'loading' | 'success' | 'error';
export default function App() {
const [data, setData] = useState<HealthResponse | null>(null);
const [status, setStatus] = useState<Status>('loading');
const [error, setError] = useState<string | null>(null);
useEffect(() => {
fetchHealth()
.then((res) => {
setData(res);
setStatus('success');
})
.catch((err: Error) => {
setError(err.message);
setStatus('error');
});
}, []);
return (
<div className="app">
<div className="hero">
<div className="hero-badge">🏙 CityGame</div>
<h1 className="hero-title">
Fullstack <span className="gradient-text">Template</span>
</h1>
<p className="hero-subtitle">
Spring Boot · React · TypeScript · NX · Docker
</p>
<div className="api-card">
<div className="api-card-header">
<span className="api-dot" data-status={status} />
<span className="api-label">API Status</span>
</div>
{status === 'loading' && (
<div className="api-body">
<div className="spinner" />
<span>Connecting to backend</span>
</div>
)}
{status === 'success' && data && (
<div className="api-body success">
<p className="api-message">{data.message}</p>
<div className="api-meta">
<span>Status: <strong>{data.status}</strong></span>
<span>Time: <strong>{new Date(data.timestamp).toLocaleTimeString()}</strong></span>
</div>
</div>
)}
{status === 'error' && (
<div className="api-body error">
<p> Backend not reachable</p>
<p className="api-error-detail">{error}</p>
<p className="api-hint">Run <code>npm run dev:backend</code> to start Spring Boot</p>
</div>
)}
</div>
<div className="stack-grid">
<div className="stack-card">
<span className="stack-icon"></span>
<span className="stack-name">Spring Boot 3</span>
<span className="stack-port">:8080</span>
</div>
<div className="stack-card">
<span className="stack-icon"></span>
<span className="stack-name">Vite + React</span>
<span className="stack-port">:5173</span>
</div>
<div className="stack-card">
<span className="stack-icon">🐘</span>
<span className="stack-name">PostgreSQL</span>
<span className="stack-port">:5432</span>
</div>
<div className="stack-card">
<span className="stack-icon">📦</span>
<span className="stack-name">NX Monorepo</span>
<span className="stack-port">cached</span>
</div>
</div>
</div>
</div>
);
}

View file

@ -0,0 +1,13 @@
export interface HealthResponse {
message: string;
timestamp: string;
status: string;
}
export async function fetchHealth(): Promise<HealthResponse> {
const response = await fetch('/api/hello');
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return response.json();
}

View file

@ -0,0 +1,60 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:root {
--bg-primary: #0a0a0f;
--bg-secondary: #111118;
--bg-card: rgba(255, 255, 255, 0.04);
--bg-card-hover: rgba(255, 255, 255, 0.07);
--border: rgba(255, 255, 255, 0.08);
--border-strong: rgba(255, 255, 255, 0.15);
--text-primary: #f0f0ff;
--text-secondary: rgba(240, 240, 255, 0.55);
--text-muted: rgba(240, 240, 255, 0.35);
--accent-blue: #4f8eff;
--accent-purple: #a855f7;
--accent-cyan: #22d3ee;
--accent-green: #34d399;
--accent-red: #f87171;
--gradient-hero: linear-gradient(135deg, #4f8eff 0%, #a855f7 50%, #22d3ee 100%);
--gradient-card: linear-gradient(135deg, rgba(79,142,255,0.1) 0%, rgba(168,85,247,0.1) 100%);
--shadow-glow: 0 0 60px rgba(79, 142, 255, 0.15);
--shadow-card: 0 4px 24px rgba(0, 0, 0, 0.4);
--radius: 16px;
--radius-sm: 8px;
}
html, body {
height: 100%;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
background-color: var(--bg-primary);
color: var(--text-primary);
line-height: 1.6;
-webkit-font-smoothing: antialiased;
overflow-x: hidden;
}
body::before {
content: '';
position: fixed;
inset: 0;
background:
radial-gradient(ellipse at 20% 20%, rgba(79, 142, 255, 0.08) 0%, transparent 50%),
radial-gradient(ellipse at 80% 80%, rgba(168, 85, 247, 0.08) 0%, transparent 50%);
pointer-events: none;
z-index: 0;
}
#root {
min-height: 100vh;
position: relative;
z-index: 1;
}

View file

@ -0,0 +1,13 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './index.css';
const root = document.getElementById('root');
if (!root) throw new Error('Root element not found');
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>
);

View file

@ -0,0 +1 @@
import '@testing-library/jest-dom';

1
apps/frontend/src/vite-env.d.ts vendored Normal file
View file

@ -0,0 +1 @@
/// <reference types="vite/client" />

View file

@ -0,0 +1,24 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"types": ["vitest/globals"]
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View file

@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}

View file

@ -0,0 +1,42 @@
/// <reference types="vitest" />
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
root: __dirname,
cacheDir: '../../node_modules/.vite/apps/frontend',
server: {
port: 5173,
host: true,
proxy: {
// Proxy all /api requests to the Spring Boot backend during dev
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
secure: false,
},
},
},
build: {
outDir: path.resolve(__dirname, '../../dist/apps/frontend'),
emptyOutDir: true,
reportCompressedSize: true,
commonjsOptions: {
transformMixedEsModules: true,
},
sourcemap: true,
},
test: {
globals: true,
environment: 'jsdom',
setupFiles: ['./src/test-setup.ts'],
include: ['src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
coverage: {
reportsDirectory: '../../coverage/apps/frontend',
provider: 'v8',
},
},
});

41
docker-compose.dev.yml Normal file
View file

@ -0,0 +1,41 @@
# ──────────────────────────────────────────────────────
# DEV — only starts the database
# Frontend and Backend run natively via NX for hot reload:
# npm run dev → nx run-many -t serve --parallel
#
# Usage: docker compose -f docker-compose.dev.yml up -d
# ──────────────────────────────────────────────────────
name: citygame-dev
services:
# ── Database (only service needed for local dev) ──
db:
image: postgres:16-alpine
container_name: citygame-dev-db
restart: unless-stopped
environment:
POSTGRES_DB: citygame
POSTGRES_USER: citygame
POSTGRES_PASSWORD: citygame
ports:
# Expose directly to localhost for IDEs and tools
- "5432:5432"
volumes:
- pgdata-dev:/var/lib/postgresql/data
networks:
- citygame-dev-net
healthcheck:
test: ["CMD-SHELL", "pg_isready -U citygame -d citygame"]
interval: 5s
timeout: 3s
retries: 5
volumes:
pgdata-dev:
driver: local
networks:
citygame-dev-net:
driver: bridge

75
docker-compose.yml Normal file
View file

@ -0,0 +1,75 @@
# ──────────────────────────────────────────────────────
# PRODUCTION — docker compose up
# Requires: npm run docker:build (or make docker:build)
# ──────────────────────────────────────────────────────
name: citygame
services:
# ── Database ──────────────────────────────────
db:
image: postgres:16-alpine
container_name: citygame-db
restart: unless-stopped
environment:
POSTGRES_DB: ${DB_NAME:-citygame}
POSTGRES_USER: ${DB_USERNAME:-citygame}
POSTGRES_PASSWORD: ${DB_PASSWORD:-citygame}
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- citygame-net
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USERNAME:-citygame} -d ${DB_NAME:-citygame}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
# ── Backend (Spring Boot) ─────────────────────
backend:
image: citygame-backend:latest
container_name: citygame-backend
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
SPRING_PROFILES_ACTIVE: prod
DB_URL: jdbc:postgresql://db:5432/${DB_NAME:-citygame}
DB_USERNAME: ${DB_USERNAME:-citygame}
DB_PASSWORD: ${DB_PASSWORD:-citygame}
CORS_ALLOWED_ORIGINS: ${CORS_ALLOWED_ORIGINS:-http://localhost}
JAVA_TOOL_OPTIONS: "-XX:+UseContainerSupport -XX:MaxRAMPercentage=75.0"
ports:
- "${BACKEND_PORT:-8080}:8080"
networks:
- citygame-net
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://localhost:8080/actuator/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
# ── Frontend (nginx) ──────────────────────────
frontend:
image: citygame-frontend:latest
container_name: citygame-frontend
restart: unless-stopped
depends_on:
backend:
condition: service_healthy
ports:
- "${FRONTEND_PORT:-80}:80"
networks:
- citygame-net
volumes:
pgdata:
driver: local
networks:
citygame-net:
driver: bridge

79
nx.json Normal file
View file

@ -0,0 +1,79 @@
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"defaultBase": "main",
"namedInputs": {
"default": [
"{projectRoot}/**/*",
"sharedGlobals"
],
"sharedGlobals": [
"{workspaceRoot}/nx.json"
],
"typescript": [
"{projectRoot}/**/*.ts",
"{projectRoot}/**/*.tsx",
"{projectRoot}/tsconfig*.json",
"{projectRoot}/package.json"
],
"java": [
"{projectRoot}/src/**/*.java",
"{projectRoot}/pom.xml",
"{projectRoot}/build.gradle*"
],
"docker": [
"{projectRoot}/Dockerfile",
"{workspaceRoot}/docker-compose*.yml"
]
},
"targetDefaults": {
"build": {
"cache": true,
"dependsOn": [
"^build"
],
"inputs": [
"default",
"^default"
]
},
"test": {
"cache": true,
"inputs": [
"default",
"^default"
]
},
"serve": {
"cache": false
},
"docker-build": {
"cache": false,
"dependsOn": [
"build"
]
},
"@nx/vite:build": {
"cache": true,
"inputs": [
"typescript",
"^typescript"
],
"outputs": [
"{options.outputPath}"
]
}
},
"plugins": [
{
"plugin": "@nx/vite/plugin",
"options": {
"buildTargetName": "build",
"serveTargetName": "serve",
"previewTargetName": "preview",
"testTargetName": "test",
"serveStaticTargetName": "serve-static"
}
}
],
"analytics": true
}

34
package.json Normal file
View file

@ -0,0 +1,34 @@
{
"name": "city-game",
"version": "0.0.1",
"private": true,
"packageManager": "pnpm@10.33.2",
"scripts": {
"dev": "nx run-many -t serve --parallel --output-style=dynamic",
"dev:frontend": "nx run frontend:serve",
"dev:backend": "nx run backend:serve",
"build": "nx run-many -t build",
"build:frontend": "nx run frontend:build",
"build:backend": "nx run backend:build",
"docker:build": "nx run-many -t docker-build",
"docker:build:frontend": "nx run frontend:docker-build",
"docker:build:backend": "nx run backend:docker-build",
"start": "docker compose up",
"start:detach": "docker compose up -d",
"stop": "docker compose down",
"logs": "docker compose logs -f",
"test": "nx run-many -t test",
"test:frontend": "nx run frontend:test",
"test:backend": "nx run backend:test",
"graph": "nx graph",
"affected:test": "nx affected -t test",
"affected:build": "nx affected -t build"
},
"devDependencies": {
"@nx/js": "^22.7.5",
"@nx/react": "^22.7.5",
"@nx/vite": "^22.7.5",
"@nxrocks/nx-spring-boot": "^11.0.0",
"nx": "^22.7.5"
}
}

8235
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load diff

2
pnpm-workspace.yaml Normal file
View file

@ -0,0 +1,2 @@
packages:
- 'apps/frontend'

20
tsconfig.base.json Normal file
View file

@ -0,0 +1,20 @@
{
"compileOnSave": false,
"compilerOptions": {
"rootDir": ".",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es2015",
"module": "esnext",
"lib": ["es2020", "dom"],
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"baseUrl": ".",
"paths": {}
},
"exclude": ["node_modules", "tmp"]
}