chore: scaffold turbo monorepo with hono api and react admin web

This commit is contained in:
Jose Selesan
2026-10-15 15:24:34 -03:00
commit 2b1d2152c4
89 changed files with 4996 additions and 0 deletions

49
apps/api/src/app.ts Normal file
View File

@@ -0,0 +1,49 @@
import { cors } from 'hono/cors'
import { Hono } from 'hono'
import { requestId } from 'hono/request-id'
import { secureHeaders } from 'hono/secure-headers'
import { auth } from '@/lib/auth'
import { logger } from '@/lib/logger'
import { errorHandler, notFoundHandler } from '@/lib/problem-details'
import { healthModule } from '@/modules/health'
import type { AppEnv } from '@/types'
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:5173')
.split(',')
.map((origin) => origin.trim())
.filter(Boolean)
export function createApp() {
const app = new Hono<AppEnv>()
app.use(secureHeaders())
app.use(cors({ origin: allowedOrigins, credentials: true }))
app.use(requestId())
app.use(async (c, next) => {
const requestLogger = logger.child({ requestId: c.get('requestId') })
c.set('logger', requestLogger)
const start = performance.now()
await next()
requestLogger.info(
{
method: c.req.method,
path: c.req.path,
status: c.res.status,
durationMs: Math.round(performance.now() - start),
},
'request',
)
})
// BetterAuth owns every route under /api/auth/*.
app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw))
app.route('/health', healthModule)
app.notFound(notFoundHandler)
app.onError(errorHandler)
return app
}

13
apps/api/src/index.ts Normal file
View File

@@ -0,0 +1,13 @@
import { createApp } from '@/app'
import { logger } from '@/lib/logger'
const port = Number(process.env.PORT ?? 3000)
const app = createApp()
logger.info({ port }, 'api listening')
export default {
port,
fetch: app.fetch,
}

21
apps/api/src/lib/auth.ts Normal file
View File

@@ -0,0 +1,21 @@
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'
import { prisma } from '@/lib/prisma'
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
.split(',')
.map((origin) => origin.trim())
.filter(Boolean)
export const auth = betterAuth({
database: prismaAdapter(prisma, { provider: 'postgresql' }),
baseURL: process.env.BETTER_AUTH_URL,
secret: process.env.BETTER_AUTH_SECRET,
trustedOrigins,
emailAndPassword: {
enabled: true,
},
})
export type Auth = typeof auth

View File

@@ -0,0 +1,21 @@
import { pino } from 'pino'
const isProduction = process.env.NODE_ENV === 'production'
/**
* Single logger instance for the whole API. Import it wherever you need to log —
* never use `console.log` in the backend.
*/
export const logger = pino({
level: process.env.LOG_LEVEL ?? (isProduction ? 'info' : 'debug'),
...(isProduction
? {}
: {
transport: {
target: 'pino-pretty',
options: { colorize: true, translateTime: 'HH:MM:ss', ignore: 'pid,hostname' },
},
}),
})
export type Logger = typeof logger

View File

@@ -0,0 +1,19 @@
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '@/generated/prisma/client'
const connectionString = process.env.DATABASE_URL
if (!connectionString) {
throw new Error('DATABASE_URL is not set. Copy apps/api/.env.example to apps/api/.env.')
}
const adapter = new PrismaPg({ connectionString })
/**
* Shared Prisma client. Import it and pass it into use cases; never create a
* client per request.
*/
export const prisma = new PrismaClient({ adapter })
export type Database = typeof prisma

View File

@@ -0,0 +1,52 @@
import { problem, problemTypes, type ProblemDetails } from '@superlist/shared'
import type { Context } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { logger } from '@/lib/logger'
/** Writes a RFC 9457 Problem Details response (`application/problem+json`). */
export function problemResponse(_c: Context, details: ProblemDetails) {
return new Response(JSON.stringify(details), {
status: details.status,
headers: { 'content-type': 'application/problem+json' },
})
}
/** Maps anything thrown inside a handler to a Problem Details response. */
export function errorHandler(error: Error, c: Context) {
if (error instanceof HTTPException) {
return problemResponse(
c,
problem({
title: error.message,
status: error.status,
detail: error.cause instanceof Error ? error.cause.message : undefined,
}),
)
}
logger.error({ err: error, path: c.req.path }, 'unhandled error')
return problemResponse(
c,
problem({
type: problemTypes.internal,
title: 'Internal Server Error',
status: 500,
detail: 'An unexpected error happened while processing the request.',
}),
)
}
/** Fallback for unmatched routes. */
export function notFoundHandler(c: Context) {
return problemResponse(
c,
problem({
type: problemTypes.notFound,
title: 'Not Found',
status: 404,
detail: `No route matches ${c.req.method} ${c.req.path}`,
}),
)
}

View File

@@ -0,0 +1,86 @@
import { describe, expect, it } from 'bun:test'
import { Failure, Ok, problems } from '@superlist/shared'
import { Hono } from 'hono'
import { z } from 'zod'
import { resultJson } from './result-json'
import { validate } from './validate'
const querySchema = z.object({
take: z.coerce.number().int().min(1).max(50).default(10),
})
function createTestApp() {
const app = new Hono()
app.get('/', validate.query(querySchema), (c) => {
const { take } = c.req.valid('query')
return resultJson(c, Ok(Array.from({ length: take }, (_, index) => index)))
})
app.get('/missing', (c) => resultJson(c, Failure(problems.notFound('No alert with that id.'))))
app.post('/created', (c) => resultJson(c, Ok({ id: 'alert_1' }), { status: 201 }))
app.delete('/gone', (c) => resultJson(c, Ok(undefined), { status: 204 }))
return app
}
describe('resultJson', () => {
const app = createTestApp()
it('serializes Ok values with 200 and parses the query with Zod', async () => {
const response = await app.request('/?take=3')
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toContain('application/json')
await expect(response.json()).resolves.toEqual([0, 1, 2])
})
it('applies schema defaults', async () => {
const response = await app.request('/')
await expect(response.json()).resolves.toHaveLength(10)
})
it('answers validation failures with Problem Details (422)', async () => {
const response = await app.request('/?take=999')
expect(response.status).toBe(422)
expect(response.headers.get('content-type')).toContain('application/problem+json')
await expect(response.json()).resolves.toMatchObject({
title: 'Validation Error',
status: 422,
errors: { take: expect.any(Array) },
})
})
it('answers Failure results with Problem Details of the error status', async () => {
const response = await app.request('/missing')
expect(response.status).toBe(404)
expect(response.headers.get('content-type')).toContain('application/problem+json')
await expect(response.json()).resolves.toMatchObject({
type: expect.stringContaining('not-found'),
title: 'Not Found',
status: 404,
detail: 'No alert with that id.',
})
})
it('honors a custom success status', async () => {
const response = await app.request('/created', { method: 'POST' })
expect(response.status).toBe(201)
await expect(response.json()).resolves.toEqual({ id: 'alert_1' })
})
it('sends an empty body for 204', async () => {
const response = await app.request('/gone', { method: 'DELETE' })
expect(response.status).toBe(204)
expect(await response.text()).toBe('')
})
})

View File

@@ -0,0 +1,39 @@
import { problem, type ProblemDetails, type Result } from '@superlist/shared'
import type { Context } from 'hono'
import { problemResponse } from '@/lib/problem-details'
type SuccessStatus = 200 | 201 | 202 | 204
/**
* Turns a use case `Result` into an HTTP response:
*
* - `Ok(value)` → `200` (or `init.status`) with the value as JSON.
* - `Failure(problem)` → the matching RFC 9457 Problem Details response.
*
* ```ts
* app.get('/', validate.query(AlertQuerySchema), async (c) => {
* const query = c.req.valid('query')
* const result = await new ListAlerts(prisma).execute(query)
*
* return resultJson(c, result)
* })
* ```
*/
export function resultJson<T>(
c: Context,
result: Result<T, ProblemDetails>,
init: { status?: SuccessStatus } = {},
) {
if (!result.ok) {
return problemResponse(c, problem(result.error))
}
const status = init.status ?? 200
if (status === 204) {
return c.body(null, 204)
}
return c.json(result.value, status)
}

View File

@@ -0,0 +1,42 @@
import { zValidator, type Hook } from '@hono/zod-validator'
import { problems, type FieldErrors } from '@superlist/shared'
import type { Context, Env, ValidationTargets } from 'hono'
import type { ZodError, ZodType } from 'zod'
/**
* Turns a validation failure into a RFC 9457 Problem Details response (422)
* instead of the lib's default `{ success: false, error }` payload.
*/
const onInvalid: Hook<unknown, Env, string> = (result, c: Context) => {
if (result.success) return
const fieldErrors: FieldErrors = {}
for (const issue of (result.error as ZodError).issues) {
const path = issue.path.length > 0 ? issue.path.map(String).join('.') : '_root'
;(fieldErrors[path] ??= []).push(issue.message)
}
return c.body(JSON.stringify(problems.validation(fieldErrors)), 422, {
'content-type': 'application/problem+json',
})
}
/**
* Zod validation middleware that answers with Problem Details.
*
* ```ts
* app.get('/', validate.query(AlertQuerySchema), (c) => {
* const query = c.req.valid('query') // fully typed from the schema
* ...
* })
* ```
*/
export const validate = {
json: <Schema extends ZodType>(schema: Schema) => zValidator('json', schema, onInvalid),
form: <Schema extends ZodType>(schema: Schema) => zValidator('form', schema, onInvalid),
query: <Schema extends ZodType>(schema: Schema) => zValidator('query', schema, onInvalid),
param: <Schema extends ZodType>(schema: Schema) => zValidator('param', schema, onInvalid),
header: <Schema extends ZodType>(schema: Schema) => zValidator('header', schema, onInvalid),
cookie: <Schema extends ZodType>(schema: Schema) => zValidator('cookie', schema, onInvalid),
} satisfies Record<keyof ValidationTargets, unknown>

View File

@@ -0,0 +1,11 @@
import { Hono } from 'hono'
import { resultJson } from '@/lib/result-json'
import type { AppEnv } from '@/types'
import { GetStatus } from './use-case'
/** GET /health — liveness probe. */
export const getStatusRoute = new Hono<AppEnv>()
getStatusRoute.get('/', (c) => resultJson(c, new GetStatus().execute()))

View File

@@ -0,0 +1,18 @@
import { describe, expect, it } from 'bun:test'
import { GetStatus } from './use-case'
describe('GetStatus', () => {
it('reports ok with the current uptime and timestamp', () => {
const now = new Date('2026-01-01T00:00:00.000Z')
const result = new GetStatus(() => now).execute()
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(result.value).toEqual({
status: 'ok',
uptimeSeconds: expect.any(Number),
timestamp: '2026-01-01T00:00:00.000Z',
})
})
})

View File

@@ -0,0 +1,23 @@
import { Ok, type Result, type ProblemDetails } from '@superlist/shared'
export type HealthStatus = {
status: 'ok'
uptimeSeconds: number
timestamp: string
}
/**
* Returns the liveness status of the process.
* No dependencies and no failure mode: it must always succeed.
*/
export class GetStatus {
constructor(private readonly now: () => Date = () => new Date()) {}
execute(): Result<HealthStatus, ProblemDetails> {
return Ok({
status: 'ok',
uptimeSeconds: Math.round(process.uptime()),
timestamp: this.now().toISOString(),
})
}
}

View File

@@ -0,0 +1,8 @@
import { Hono } from 'hono'
import type { AppEnv } from '@/types'
import { getStatusRoute } from './get-status/route'
/** `health` module: every feature of the module is mounted here. */
export const healthModule = new Hono<AppEnv>().route('/', getStatusRoute)

9
apps/api/src/types.ts Normal file
View File

@@ -0,0 +1,9 @@
import type { Logger } from '@/lib/logger'
/** Hono environment shared by every route: `c.get('logger')`, `c.get('requestId')`. */
export type AppEnv = {
Variables: {
logger: Logger
requestId: string
}
}