All files / routes/marketplace stats.routes.ts

100% Statements 10/10
100% Branches 8/8
100% Functions 2/2
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63                                1x     1x 4x 4x 4x   4x         2x                               2x                   3x   1x          
// Public Marketplace Stats Route (API Key Protected)
import { Hono } from "hono";
import { pros } from "../../db/schema/pros";
import { projects } from "../../db/schema/projects";
import { inquiries } from "../../db/schema/inquiries";
import { cities } from "../../db/schema/locations";
import { eq, sql } from "drizzle-orm";
import { handleError, success } from "../../lib/response";
import { CACHE_TTL, CACHE_KEYS } from "../../lib/cache";
import type { ContextVariables } from "../../middleware";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: ContextVariables;
};
 
const stats = new Hono<Env>();
 
// GET /api/marketplace/stats — aggregate platform stats
stats.get("/", async (c) => {
	try {
		const db = c.get("db");
		const cache = c.get("cache");
 
		const data = await cache.getOrSet(
			CACHE_KEYS.MARKETPLACE_STATS,
			async () => {
				// Three simple COUNT(*) queries + cities count, run in parallel
				const [prosResult, projectsResult, inquiriesResult, citiesResult] =
					await Promise.all([
						db
							.select({ count: sql<number>`count(*)` })
							.from(pros)
							.where(eq(pros.status, "published")),
						db
							.select({ count: sql<number>`count(*)` })
							.from(projects)
							.where(eq(projects.status, "published")),
						db.select({ count: sql<number>`count(*)` }).from(inquiries),
						db
							.select({ count: sql<number>`count(*)` })
							.from(cities)
							.where(eq(cities.isActive, true)),
					]);
 
				return {
					prosCount: prosResult[0]?.count ?? 0,
					projectsCount: projectsResult[0]?.count ?? 0,
					inquiriesCount: inquiriesResult[0]?.count ?? 0,
					citiesServed: citiesResult[0]?.count ?? 0,
				};
			},
			{ l1Ttl: CACHE_TTL.STATS_L1, l2Ttl: 3600 },
		);
 
		return success(c, data);
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default stats;