All files / routes/taxonomy locations.routes.ts

100% Statements 30/30
100% Branches 2/2
100% Functions 7/7
100% Lines 28/28

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 64 65 66 67 68 69 70 71 72 73 74                          2x     2x 5x 5x 5x 5x     4x   1x         2x 4x 4x 4x 4x     2x   3x   1x         2x 5x 5x 5x 5x       2x     2x 1x 2x       1x     4x   1x          
// Taxonomy Location Routes - Nested geographic hierarchy endpoints
import { Hono } from "hono";
import { eq } from "drizzle-orm";
import { getDb } from "../../db";
import { zones, localities } from "../../db/schema";
import { success, handleError } from "../../lib/response";
import { queryActiveTaxonomy, cachedTaxonomyQuery } from "./helpers";
import { MARKETPLACE } from "../../lib/cache";
 
type Env = {
	Bindings: CloudflareBindings;
};
 
const locations = new Hono<Env>();
 
// GET /cities/:cityId/zones
locations.get("/cities/:cityId/zones", async (c) => {
	try {
		const db = getDb(c.env.DB);
		const cityId = c.req.param("cityId");
		const data = await cachedTaxonomyQuery(c, MARKETPLACE.taxonomyZones(cityId), () =>
			queryActiveTaxonomy(db, zones, eq(zones.cityId, cityId)),
		);
		return success(c, data);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// GET /zones/:zoneId/localities
locations.get("/zones/:zoneId/localities", async (c) => {
	try {
		const db = getDb(c.env.DB);
		const zoneId = c.req.param("zoneId");
		const data = await cachedTaxonomyQuery(
			c,
			`taxonomy:localities:${zoneId}`,
			() => queryActiveTaxonomy(db, localities, eq(localities.zoneId, zoneId)),
		);
		return success(c, data);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// GET /cities/:cityId/localities - All localities for a city (eliminates N+1)
locations.get("/cities/:cityId/localities", async (c) => {
	try {
		const db = getDb(c.env.DB);
		const cityId = c.req.param("cityId");
		const data = await cachedTaxonomyQuery(
			c,
			`taxonomy:localities-by-city:${cityId}`,
			async () => {
				const cityZones = await queryActiveTaxonomy<{
					id: string;
				}>(db, zones, eq(zones.cityId, cityId));
				if (cityZones.length === 0) return [];
				const results = await Promise.all(
					cityZones.map((z) =>
						queryActiveTaxonomy(db, localities, eq(localities.zoneId, z.id)),
					),
				);
				return results.flat();
			},
		);
		return success(c, data);
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default locations;