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

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>