Files
CoHaiSe-CLOUD/backend/src/utils/http.ts
T
Gitea ActionsandEsiah f689ab4d57
CD — Deployment / deploy (push) Successful in 34s
refactor: restructure frontend and backend by domain services (#26)
Split the monolithic backend (lib/, routes/, access.ts, storage.ts, media.ts)
into a layered structure inspired by JeanXXIII-CRM:
- config/: appConfig, db
- middleware/: auth (session, roles, cookies)
- models/: shared types
- routes/: *Routes.ts (thin HTTP handlers)
- services/: *Service.ts (business logic, one per domain)
- utils/: errors, http, migrate, ratelimit, validators, service bootstrap

Frontend likewise: services/*Service.ts + apiClient, contexts/, types/, utils/format.
Route files now carry the "Routes" suffix; service files are named
authService.ts, ratelimit.ts, etc. and live in their own files, frontend and
backend separated.

Updated docs and READMEs to reflect the new layout. Typecheck and builds pass.

---------

Co-authored-by: xEsiah <[email protected]>
Reviewed-on: #26
Reviewed-by: Esiah <[email protected]>
Co-authored-by: Gitea Actions <-[email protected]>
2026-11-13 09:13:27 +00:00

206 lines
6.0 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { Hono, type Context, type Next } from "hono";
import { cors } from "hono/cors";
import type { SessionUser } from "../models/types.js";
import type { Config } from "../config/appConfig.js";
import type { Db } from "../config/db.js";
import { AppError, toSafeError } from "./errors.js";
export interface Logger {
level: Config["LOG_LEVEL"];
info: (message: string, fields?: Record<string, unknown>) => void;
warn: (message: string, fields?: Record<string, unknown>) => void;
error: (message: string, fields?: Record<string, unknown>) => void;
debug: (message: string, fields?: Record<string, unknown>) => void;
}
const ORDER: Record<Config["LOG_LEVEL"], number> = {
silent: 0,
error: 1,
warn: 2,
info: 3,
debug: 4,
};
export const createLogger = (level: Config["LOG_LEVEL"], service: string): Logger => {
const emit = (name: keyof typeof ORDER, message: string, fields?: Record<string, unknown>) => {
if (ORDER[name] > ORDER[level]) return;
const line = JSON.stringify({
ts: new Date().toISOString(),
level: name,
service,
msg: message,
...fields,
});
if (name === "error") console.error(line);
else console.log(line);
};
return {
level,
info: (message, fields) => emit("info", message, fields),
warn: (message, fields) => emit("warn", message, fields),
error: (message, fields) => emit("error", message, fields),
debug: (message, fields) => emit("debug", message, fields),
};
};
export interface AppEnv {
Variables: {
requestId: string;
user?: SessionUser;
token?: string;
};
}
export type App = Hono<AppEnv>;
export const clientIp = (context: Context, trustProxy: boolean): string | null => {
if (trustProxy) {
const forwarded = context.req.header("x-forwarded-for");
const first = forwarded?.split(",")[0]?.trim();
if (first) return first.slice(0, 45);
}
const env = context.env as
| { incoming?: { socket?: { remoteAddress?: string } } }
| undefined;
const address = env?.incoming?.socket?.remoteAddress;
return address ? address.slice(0, 45) : null;
};
export const JSON_BODY_MAX_BYTES = 1024 * 1024;
export const readBodyCapped = async (context: Context, maxBytes: number): Promise<Buffer> => {
const declared = Number(context.req.header("content-length") ?? "");
if (Number.isFinite(declared) && declared > maxBytes) {
throw AppError.payloadTooLarge("Corps de requete trop volumineux.");
}
const body = context.req.raw.body;
if (body === null) return Buffer.alloc(0);
const chunks: Uint8Array[] = [];
let received = 0;
const reader = body.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
received += value.byteLength;
if (received > maxBytes) {
await reader.cancel().catch(() => undefined);
throw AppError.payloadTooLarge("Corps de requete trop volumineux.");
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
return Buffer.concat(chunks);
};
export const readJson = async (
context: Context,
maxBytes = JSON_BODY_MAX_BYTES,
): Promise<unknown> => {
const buffer = await readBodyCapped(context, maxBytes);
if (buffer.byteLength === 0) return null;
try {
return JSON.parse(buffer.toString("utf8")) as unknown;
} catch {
return null;
}
};
export interface RouteDeps {
db: Db;
config: Config;
logger: Logger;
}
export interface AppOptions {
service: string;
config: Config;
db: Db;
logger: Logger;
routes: (app: App, deps: RouteDeps) => void;
probeDb?: boolean;
}
export const createApp = ({ service, config, db, logger, routes, probeDb = true }: AppOptions): App => {
const app = new Hono<AppEnv>();
app.use("*", async (context: Context, next: Next) => {
const requestId = context.req.header("x-request-id") ?? randomUUID();
context.set("requestId", requestId);
context.res.headers.set("x-request-id", requestId);
context.res.headers.set("x-content-type-options", "nosniff");
context.res.headers.set("referrer-policy", "same-origin");
context.res.headers.set("x-frame-options", "DENY");
const started = performance.now();
await next();
const duration = Math.round(performance.now() - started);
if (context.req.method !== "OPTIONS") {
logger.debug("requete", {
requestId,
method: context.req.method,
path: new URL(context.req.url).pathname,
status: context.res.status,
durationMs: duration,
});
}
});
if (config.CORS_ORIGIN) {
app.use(
"*",
cors({
origin: config.CORS_ORIGIN.split(",").map((value) => value.trim()),
credentials: true,
maxAge: 600,
}),
);
}
app.get("/healthz", async (context) => {
if (!probeDb) return context.json({ status: "ok", service }, 200);
const started = performance.now();
try {
await db.query("SELECT 1");
return context.json(
{ status: "ok", service, db: "up", latencyMs: Math.round(performance.now() - started) },
200,
);
} catch (error) {
logger.error("sante base en echec", { error: String(error) });
return context.json({ status: "degraded", service, db: "down" }, 503);
}
});
routes(app, { db, config, logger });
app.notFound((context) =>
context.json({ error: { status: 404, code: "NOT_FOUND", message: "Route introuvable." } }, 404),
);
app.onError((error, context) => {
const safe = toSafeError(error);
const requestId = context.get("requestId");
if (safe.status >= 500) {
logger.error("erreur non geree", {
requestId,
code: safe.code,
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
});
} else {
logger.debug("refus", { requestId, code: safe.code, status: safe.status });
}
return context.json({ error: { ...safe, requestId } }, safe.status as 500);
});
return app;
};
export { AppError };