create-rr-stack 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/index.ts +48 -0
  3. package/package.json +34 -4
  4. package/scaffold.ts +88 -0
  5. package/template/.env.example +3 -0
  6. package/template/.github/workflows/ci.yml +38 -0
  7. package/template/AGENTS.md +44 -0
  8. package/template/CLAUDE.md +1 -0
  9. package/template/LICENSE +21 -0
  10. package/template/README.md +58 -0
  11. package/template/_gitignore +7 -0
  12. package/template/compose.yml +17 -0
  13. package/template/openapi.json +137 -0
  14. package/template/scripts/check.sh +49 -0
  15. package/template/scripts/smoke.sh +31 -0
  16. package/template/server/.sqlx/query-2abc65ebb76339a9d9a9d09820c9cdd6ceba212593a9641b80cda81df39e2fed.json +64 -0
  17. package/template/server/.sqlx/query-4713cdeecf4c3beeef699a78fc6f52857ba3a8f357565ba00d1d97095057e0f5.json +62 -0
  18. package/template/server/Cargo.lock +2135 -0
  19. package/template/server/Cargo.toml +34 -0
  20. package/template/server/clippy.toml +2 -0
  21. package/template/server/migrations/0001_todos.sql +6 -0
  22. package/template/server/src/bin/openapi.rs +4 -0
  23. package/template/server/src/health.rs +15 -0
  24. package/template/server/src/lib.rs +80 -0
  25. package/template/server/src/main.rs +22 -0
  26. package/template/server/src/todos.rs +94 -0
  27. package/template/server/tests/health.rs +31 -0
  28. package/template/server/tests/todos.rs +83 -0
  29. package/template/web/_gitignore +7 -0
  30. package/template/web/app/api/@tanstack/react-query.gen.ts +84 -0
  31. package/template/web/app/api/client/client.gen.ts +277 -0
  32. package/template/web/app/api/client/index.ts +27 -0
  33. package/template/web/app/api/client/types.gen.ts +218 -0
  34. package/template/web/app/api/client/utils.gen.ts +316 -0
  35. package/template/web/app/api/client.gen.ts +16 -0
  36. package/template/web/app/api/core/auth.gen.ts +48 -0
  37. package/template/web/app/api/core/bodySerializer.gen.ts +82 -0
  38. package/template/web/app/api/core/params.gen.ts +178 -0
  39. package/template/web/app/api/core/pathSerializer.gen.ts +171 -0
  40. package/template/web/app/api/core/queryKeySerializer.gen.ts +117 -0
  41. package/template/web/app/api/core/serverSentEvents.gen.ts +242 -0
  42. package/template/web/app/api/core/types.gen.ts +110 -0
  43. package/template/web/app/api/core/utils.gen.ts +140 -0
  44. package/template/web/app/api/index.ts +4 -0
  45. package/template/web/app/api/sdk.gen.ts +32 -0
  46. package/template/web/app/api/types.gen.ts +74 -0
  47. package/template/web/app/app.css +15 -0
  48. package/template/web/app/root.tsx +82 -0
  49. package/template/web/app/routes/home.tsx +21 -0
  50. package/template/web/app/routes/todos.tsx +47 -0
  51. package/template/web/app/routes.ts +6 -0
  52. package/template/web/bun.lock +572 -0
  53. package/template/web/openapi-ts.config.ts +11 -0
  54. package/template/web/package.json +30 -0
  55. package/template/web/public/favicon.ico +0 -0
  56. package/template/web/react-router.config.ts +7 -0
  57. package/template/web/tsconfig.json +26 -0
  58. package/template/web/vite.config.ts +13 -0
  59. package/README.md +0 -3
@@ -0,0 +1,34 @@
1
+ [package]
2
+ name = "rr-server"
3
+ version = "0.1.0"
4
+ edition = "2024"
5
+
6
+ # The lib and binary are always called `server`, so renaming the package (create-rr-stack does) never touches code.
7
+ [lib]
8
+ name = "server"
9
+
10
+ [[bin]]
11
+ name = "server"
12
+ path = "src/main.rs"
13
+
14
+ [dependencies]
15
+ axum = "0.8.9"
16
+ chrono = { version = "0.4.45", default-features = false, features = ["std", "clock", "serde"] }
17
+ dotenvy = "0.15.7"
18
+ serde = { version = "1.0.229", features = ["derive"] }
19
+ serde_json = "1.0.154"
20
+ sqlx = { version = "0.9.1", default-features = false, features = ["postgres", "runtime-tokio", "tls-rustls", "macros", "migrate", "chrono"] }
21
+ tokio = { version = "1.54.1", features = ["full"] }
22
+ tower-http = { version = "0.7.1", features = ["fs"] }
23
+ tracing = "0.1.44"
24
+ tracing-subscriber = "0.3.23"
25
+ utoipa = "6.0.0"
26
+ utoipa-axum = "0.3.0"
27
+
28
+ [dev-dependencies]
29
+ http-body-util = "0.1.5"
30
+ tower = { version = "0.5.3", features = ["util"] }
31
+
32
+ [lints.clippy]
33
+ unwrap_used = "deny"
34
+ expect_used = "deny"
@@ -0,0 +1,2 @@
1
+ allow-unwrap-in-tests = true
2
+ allow-expect-in-tests = true
@@ -0,0 +1,6 @@
1
+ CREATE TABLE todos (
2
+ id bigserial PRIMARY KEY,
3
+ title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 200),
4
+ done boolean NOT NULL DEFAULT false,
5
+ created_at timestamptz NOT NULL DEFAULT now()
6
+ );
@@ -0,0 +1,4 @@
1
+ fn main() -> Result<(), serde_json::Error> {
2
+ println!("{}", server::openapi().to_pretty_json()?);
3
+ Ok(())
4
+ }
@@ -0,0 +1,15 @@
1
+ use axum::Json;
2
+ use serde::Serialize;
3
+ use utoipa::ToSchema;
4
+
5
+ #[derive(Serialize, ToSchema)]
6
+ pub struct Health {
7
+ pub status: String,
8
+ }
9
+
10
+ #[utoipa::path(get, path = "/health", operation_id = "health", responses((status = OK, body = Health)))]
11
+ pub async fn health() -> Json<Health> {
12
+ Json(Health {
13
+ status: "ok".into(),
14
+ })
15
+ }
@@ -0,0 +1,80 @@
1
+ mod health;
2
+ mod todos;
3
+
4
+ use std::path::PathBuf;
5
+
6
+ use axum::http::StatusCode;
7
+ use axum::response::{IntoResponse, Response};
8
+ use axum::routing::any;
9
+ use axum::{Json, Router};
10
+ use serde_json::{Value, json};
11
+ use sqlx::PgPool;
12
+ use tower_http::services::{ServeDir, ServeFile};
13
+ use utoipa::openapi::OpenApi;
14
+ use utoipa_axum::router::OpenApiRouter;
15
+ use utoipa_axum::routes;
16
+
17
+ #[derive(Clone)]
18
+ pub struct AppState {
19
+ pub db: PgPool,
20
+ }
21
+
22
+ /// Every API route is registered here; the OpenAPI spec and the runtime router both come from it.
23
+ pub fn api_router() -> OpenApiRouter<AppState> {
24
+ let api = OpenApiRouter::new()
25
+ .routes(routes!(health::health))
26
+ .routes(routes!(todos::list_todos, todos::create_todo));
27
+ OpenApiRouter::new().nest("/api", api)
28
+ }
29
+
30
+ pub fn openapi() -> OpenApi {
31
+ api_router().split_for_parts().1
32
+ }
33
+
34
+ /// `web_dist` is the React Router `build/client` dir; `None` serves the API only (tests).
35
+ pub fn app(state: AppState, web_dist: Option<PathBuf>) -> Router {
36
+ let (router, _) = api_router().split_for_parts();
37
+ let router = router
38
+ .route("/api", any(json_404))
39
+ .route("/api/", any(json_404))
40
+ .route("/api/{*rest}", any(json_404))
41
+ .with_state(state);
42
+ match web_dist {
43
+ // Prerendered pages are real files; any other path gets the SPA shell so deep links work.
44
+ Some(dir) => {
45
+ let spa = ServeFile::new(dir.join("__spa-fallback.html"));
46
+ router.fallback_service(ServeDir::new(dir).fallback(spa))
47
+ }
48
+ None => router,
49
+ }
50
+ }
51
+
52
+ /// Errors a handler can return; logged server-side, never leaked to the client.
53
+ pub enum AppError {
54
+ Db(sqlx::Error),
55
+ }
56
+
57
+ impl From<sqlx::Error> for AppError {
58
+ fn from(err: sqlx::Error) -> Self {
59
+ Self::Db(err)
60
+ }
61
+ }
62
+
63
+ impl IntoResponse for AppError {
64
+ fn into_response(self) -> Response {
65
+ match self {
66
+ Self::Db(err) => {
67
+ tracing::error!(%err, "database error");
68
+ (
69
+ StatusCode::INTERNAL_SERVER_ERROR,
70
+ Json(json!({ "error": "internal error" })),
71
+ )
72
+ .into_response()
73
+ }
74
+ }
75
+ }
76
+ }
77
+
78
+ async fn json_404() -> (StatusCode, Json<Value>) {
79
+ (StatusCode::NOT_FOUND, Json(json!({ "error": "not found" })))
80
+ }
@@ -0,0 +1,22 @@
1
+ use std::path::PathBuf;
2
+
3
+ use server::{AppState, app};
4
+
5
+ #[tokio::main]
6
+ async fn main() -> Result<(), Box<dyn std::error::Error>> {
7
+ tracing_subscriber::fmt::init();
8
+ // `cargo run` from server/ picks up the repo-root .env; real env vars still win.
9
+ dotenvy::from_filename("../.env").ok();
10
+ let database_url = std::env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
11
+ let port = std::env::var("PORT").unwrap_or_else(|_| "3000".into());
12
+ let web_dist =
13
+ PathBuf::from(std::env::var("WEB_DIST").unwrap_or_else(|_| "../web/build/client".into()));
14
+
15
+ let db = sqlx::PgPool::connect(&database_url).await?;
16
+ sqlx::migrate!().run(&db).await?;
17
+
18
+ let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")).await?;
19
+ tracing::info!("listening on {}", listener.local_addr()?);
20
+ axum::serve(listener, app(AppState { db }, Some(web_dist))).await?;
21
+ Ok(())
22
+ }
@@ -0,0 +1,94 @@
1
+ use axum::Json;
2
+ use axum::extract::State;
3
+ use axum::http::StatusCode;
4
+ use chrono::{DateTime, Utc};
5
+ use serde::{Deserialize, Serialize};
6
+ use utoipa::ToSchema;
7
+
8
+ use crate::{AppError, AppState};
9
+
10
+ /// A title that is already trimmed and 1..=200 characters; it cannot be built any other way.
11
+ #[derive(Deserialize, ToSchema)]
12
+ #[serde(try_from = "String")]
13
+ #[schema(value_type = String, min_length = 1, max_length = 200)]
14
+ pub struct TodoTitle(String);
15
+
16
+ impl TryFrom<String> for TodoTitle {
17
+ type Error = &'static str;
18
+
19
+ fn try_from(raw: String) -> Result<Self, Self::Error> {
20
+ let title = raw.trim();
21
+ match title.chars().count() {
22
+ 0 => Err("title must not be empty"),
23
+ 1..=200 => Ok(Self(title.to_owned())),
24
+ _ => Err("title must be at most 200 characters"),
25
+ }
26
+ }
27
+ }
28
+
29
+ #[derive(Deserialize, ToSchema)]
30
+ pub struct NewTodo {
31
+ pub title: TodoTitle,
32
+ }
33
+
34
+ #[derive(Serialize, ToSchema)]
35
+ pub struct Todo {
36
+ pub id: i64,
37
+ pub title: String,
38
+ pub done: bool,
39
+ /// RFC 3339 timestamp.
40
+ pub created_at: String,
41
+ }
42
+
43
+ struct TodoRow {
44
+ id: i64,
45
+ title: String,
46
+ done: bool,
47
+ created_at: DateTime<Utc>,
48
+ }
49
+
50
+ impl From<TodoRow> for Todo {
51
+ fn from(row: TodoRow) -> Self {
52
+ Self {
53
+ id: row.id,
54
+ title: row.title,
55
+ done: row.done,
56
+ created_at: row.created_at.to_rfc3339(),
57
+ }
58
+ }
59
+ }
60
+
61
+ #[utoipa::path(get, path = "/todos", operation_id = "listTodos", responses((status = OK, body = Vec<Todo>)))]
62
+ pub async fn list_todos(State(state): State<AppState>) -> Result<Json<Vec<Todo>>, AppError> {
63
+ let rows = sqlx::query_as!(
64
+ TodoRow,
65
+ "SELECT id, title, done, created_at FROM todos ORDER BY created_at DESC, id DESC"
66
+ )
67
+ .fetch_all(&state.db)
68
+ .await?;
69
+ Ok(Json(rows.into_iter().map(Todo::from).collect()))
70
+ }
71
+
72
+ #[utoipa::path(
73
+ post,
74
+ path = "/todos",
75
+ operation_id = "createTodo",
76
+ request_body = NewTodo,
77
+ responses(
78
+ (status = CREATED, body = Todo),
79
+ (status = UNPROCESSABLE_ENTITY, description = "title is empty or longer than 200 characters"),
80
+ )
81
+ )]
82
+ pub async fn create_todo(
83
+ State(state): State<AppState>,
84
+ Json(new): Json<NewTodo>,
85
+ ) -> Result<(StatusCode, Json<Todo>), AppError> {
86
+ let row = sqlx::query_as!(
87
+ TodoRow,
88
+ "INSERT INTO todos (title) VALUES ($1) RETURNING id, title, done, created_at",
89
+ new.title.0
90
+ )
91
+ .fetch_one(&state.db)
92
+ .await?;
93
+ Ok((StatusCode::CREATED, Json(row.into())))
94
+ }
@@ -0,0 +1,31 @@
1
+ #![allow(clippy::unwrap_used)] // integration-test helpers sit outside #[test] fns, which allow-unwrap-in-tests does not cover
2
+
3
+ use axum::body::Body;
4
+ use axum::http::{Request, StatusCode};
5
+ use http_body_util::BodyExt;
6
+ use serde_json::{Value, json};
7
+ use server::{AppState, app, openapi};
8
+ use sqlx::PgPool;
9
+ use tower::ServiceExt;
10
+
11
+ #[sqlx::test]
12
+ async fn health_ok(db: PgPool) {
13
+ let res = app(AppState { db }, None)
14
+ .oneshot(Request::get("/api/health").body(Body::empty()).unwrap())
15
+ .await
16
+ .unwrap();
17
+ assert_eq!(res.status(), StatusCode::OK);
18
+ let body: Value =
19
+ serde_json::from_slice(&res.into_body().collect().await.unwrap().to_bytes()).unwrap();
20
+ assert_eq!(body, json!({"status": "ok"}));
21
+ }
22
+
23
+ #[test]
24
+ fn openapi_lists_health() {
25
+ let spec = serde_json::to_value(openapi()).unwrap();
26
+ assert!(
27
+ spec["paths"]["/api/health"].is_object(),
28
+ "spec paths: {}",
29
+ spec["paths"]
30
+ );
31
+ }
@@ -0,0 +1,83 @@
1
+ #![allow(clippy::unwrap_used)] // integration-test helpers sit outside #[test] fns, which allow-unwrap-in-tests does not cover
2
+
3
+ use axum::body::Body;
4
+ use axum::http::{Request, StatusCode, header};
5
+ use axum::response::Response;
6
+ use http_body_util::BodyExt;
7
+ use serde_json::{Value, json};
8
+ use server::{AppState, app};
9
+ use sqlx::PgPool;
10
+ use tower::ServiceExt;
11
+
12
+ async fn send(db: &PgPool, req: Request<Body>) -> Response {
13
+ app(AppState { db: db.clone() }, None)
14
+ .oneshot(req)
15
+ .await
16
+ .unwrap()
17
+ }
18
+
19
+ async fn json_body(res: Response) -> Value {
20
+ serde_json::from_slice(&res.into_body().collect().await.unwrap().to_bytes()).unwrap()
21
+ }
22
+
23
+ fn post(title: &str) -> Request<Body> {
24
+ Request::post("/api/todos")
25
+ .header(header::CONTENT_TYPE, "application/json")
26
+ .body(Body::from(json!({ "title": title }).to_string()))
27
+ .unwrap()
28
+ }
29
+
30
+ fn list() -> Request<Body> {
31
+ Request::get("/api/todos").body(Body::empty()).unwrap()
32
+ }
33
+
34
+ #[sqlx::test]
35
+ async fn create_then_list(db: PgPool) {
36
+ let res = send(&db, post(" buy ice ")).await;
37
+ assert_eq!(res.status(), StatusCode::CREATED);
38
+ let created = json_body(res).await;
39
+ assert_eq!(created["title"], "buy ice");
40
+ assert_eq!(created["done"], false);
41
+
42
+ let todos = json_body(send(&db, list()).await).await;
43
+ assert_eq!(todos.as_array().map(Vec::len), Some(1));
44
+ assert_eq!(todos[0]["id"], created["id"]);
45
+ }
46
+
47
+ #[sqlx::test]
48
+ async fn rejects_empty_and_blank(db: PgPool) {
49
+ for title in ["", " "] {
50
+ let res = send(&db, post(title)).await;
51
+ assert_eq!(
52
+ res.status(),
53
+ StatusCode::UNPROCESSABLE_ENTITY,
54
+ "title {title:?}"
55
+ );
56
+ }
57
+ assert_eq!(json_body(send(&db, list()).await).await, json!([]));
58
+ }
59
+
60
+ #[sqlx::test]
61
+ async fn rejects_201_chars(db: PgPool) {
62
+ let res = send(&db, post(&"ก".repeat(201))).await;
63
+ assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
64
+ let res = send(&db, post(&"ก".repeat(200))).await;
65
+ assert_eq!(
66
+ res.status(),
67
+ StatusCode::CREATED,
68
+ "200 Thai chars is 600 bytes and must pass"
69
+ );
70
+ }
71
+
72
+ #[sqlx::test]
73
+ async fn unknown_api_path_is_json_404(db: PgPool) {
74
+ for path in ["/api", "/api/", "/api/nope"] {
75
+ let res = send(&db, Request::get(path).body(Body::empty()).unwrap()).await;
76
+ assert_eq!(res.status(), StatusCode::NOT_FOUND, "{path}");
77
+ let ct = res.headers()[header::CONTENT_TYPE].to_str().unwrap();
78
+ assert!(
79
+ ct.starts_with("application/json"),
80
+ "{path} content-type {ct}"
81
+ );
82
+ }
83
+ }
@@ -0,0 +1,7 @@
1
+ .DS_Store
2
+ .env
3
+ /node_modules/
4
+
5
+ # React Router
6
+ /.react-router/
7
+ /build/
@@ -0,0 +1,84 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ import { type DefaultError, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
4
+
5
+ import { client } from '../client.gen';
6
+ import { createTodo, health, listTodos, type Options } from '../sdk.gen';
7
+ import type { CreateTodoData, CreateTodoResponse, HealthData, HealthResponse, ListTodosData, ListTodosResponse } from '../types.gen';
8
+
9
+ export type QueryKey<TOptions extends Options> = [
10
+ Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
11
+ _id: string;
12
+ _infinite?: boolean;
13
+ tags?: ReadonlyArray<string>;
14
+ }
15
+ ];
16
+
17
+ const createQueryKey = <TOptions extends Options>(id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray<string>): [
18
+ QueryKey<TOptions>[0]
19
+ ] => {
20
+ const params: QueryKey<TOptions>[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey<TOptions>[0];
21
+ if (infinite) {
22
+ params._infinite = infinite;
23
+ }
24
+ if (tags) {
25
+ params.tags = tags;
26
+ }
27
+ if (options?.body) {
28
+ params.body = options.body;
29
+ }
30
+ if (options?.headers) {
31
+ params.headers = options.headers;
32
+ }
33
+ if (options?.path) {
34
+ params.path = options.path;
35
+ }
36
+ if (options?.query) {
37
+ params.query = options.query;
38
+ }
39
+ return [params];
40
+ };
41
+
42
+ export const healthQueryKey = (options?: Options<HealthData>) => createQueryKey('health', options);
43
+
44
+ export const healthOptions = (options?: Options<HealthData>) => queryOptions<HealthResponse, DefaultError, HealthResponse, ReturnType<typeof healthQueryKey>>({
45
+ queryFn: async ({ queryKey, signal }) => {
46
+ const { data } = await health({
47
+ ...options,
48
+ ...queryKey[0],
49
+ signal,
50
+ throwOnError: true
51
+ });
52
+ return data;
53
+ },
54
+ queryKey: healthQueryKey(options)
55
+ });
56
+
57
+ export const listTodosQueryKey = (options?: Options<ListTodosData>) => createQueryKey('listTodos', options);
58
+
59
+ export const listTodosOptions = (options?: Options<ListTodosData>) => queryOptions<ListTodosResponse, DefaultError, ListTodosResponse, ReturnType<typeof listTodosQueryKey>>({
60
+ queryFn: async ({ queryKey, signal }) => {
61
+ const { data } = await listTodos({
62
+ ...options,
63
+ ...queryKey[0],
64
+ signal,
65
+ throwOnError: true
66
+ });
67
+ return data;
68
+ },
69
+ queryKey: listTodosQueryKey(options)
70
+ });
71
+
72
+ export const createTodoMutation = (options?: Partial<Options<CreateTodoData>>): UseMutationOptions<CreateTodoResponse, DefaultError, Options<CreateTodoData>> => {
73
+ const mutationOptions: UseMutationOptions<CreateTodoResponse, DefaultError, Options<CreateTodoData>> = {
74
+ mutationFn: async (fnOptions) => {
75
+ const { data } = await createTodo({
76
+ ...options,
77
+ ...fnOptions,
78
+ throwOnError: true
79
+ });
80
+ return data;
81
+ }
82
+ };
83
+ return mutationOptions;
84
+ };