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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | 1x 4x 2x 2x 2x 2x 1x 3x 3x 3x 3x 2x 3x 3x 1x 1x 1x 8x 8x 8x 8x 8x 8x 3x 5x 5x 1x 4x 4x 1x 3x 1x 2x 2x 2x 8x 2x | // Admin marketplace-home-page curation endpoints.
//
// Two levers:
// - PUT /home-page/hero — singleton "hero project" override (one row max).
// - GET /home-page — returns {hero, featured} for the portal UI to
// render the current curation state.
//
// The "featured projects" toggle reuses the existing endpoint
// PUT /admin/projects/:id/featured (admin/projects.routes.ts:160), which
// already flips projects.is_featured and invalidates the homepage cache.
import { and, desc, eq } from "drizzle-orm";
import { Hono, type Context } from "hono";
import { z } from "zod";
import type { Dal } from "../../dal";
import { getDb } from "../../db";
import * as schema from "../../db/schema";
import { NotFoundError } from "../../lib/errors";
import { CACHE_KEYS, createDualCache } from "../../lib/cache";
import { logger } from "../../lib/logger";
import { handleError, success } from "../../lib/response";
import { requireUser } from "../../lib/utils";
import type { Services } from "../../services";
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
};
};
const homePage = new Hono<Env>();
// Shape returned to the admin UI: the minimum needed to render a "currently
// curated" panel without a second round-trip per row. Full project rows are
// available via GET /admin/projects/:id when the picker needs more.
type AdminHomePageProjectSummary = {
id: string;
title: string;
slug: string | null;
status: string;
coverImage: string | null;
proId: string;
isFeatured: boolean;
isHero: boolean;
};
function summarize(row: typeof schema.projects.$inferSelect): AdminHomePageProjectSummary {
return {
id: row.id,
title: row.title,
slug: row.slug,
status: row.status,
coverImage: row.coverImage,
proId: row.proId,
isFeatured: row.isFeatured,
isHero: row.isHero,
};
}
function invalidateHomepageCache(c: Context<Env>) {
try {
const cache = createDualCache(c.env.KV_CACHE);
const hour = new Date().getUTCHours();
c.executionCtx.waitUntil(
Promise.all([
cache.delete(`${CACHE_KEYS.MARKETPLACE_HOMEPAGE}:h${hour}`),
cache.delete(CACHE_KEYS.MARKETPLACE_HOMEPAGE),
]).catch((err) => {
logger.error("[admin/home-page] cache invalidation failed", err);
}),
);
} catch {
/* executionCtx unavailable in tests */
}
}
// ============================================================================
// GET /home-page — current curation state
// ============================================================================
homePage.get("/", async (c) => {
try {
requireUser(c.get("user"));
const db = getDb(c.env.DB);
const [heroRows, featuredRows] = await Promise.all([
db
.select()
.from(schema.projects)
.where(eq(schema.projects.isHero, true))
.limit(1),
db
.select()
.from(schema.projects)
.where(
and(
eq(schema.projects.isFeatured, true),
eq(schema.projects.status, "published"),
),
)
.orderBy(
desc(schema.projects.qualityScore),
desc(schema.projects.dateCreated),
)
.limit(24),
]);
const hero = heroRows[0] ? summarize(heroRows[0]) : null;
const featured = featuredRows.map(summarize);
return success(c, { hero, featured });
} catch (err) {
return handleError(c, err);
}
});
// ============================================================================
// PUT /home-page/hero — set / clear the singleton hero project
// ============================================================================
//
// Body: { projectId: string | null }
// - null → clear any current hero (atomic single UPDATE).
// - "id" → atomically demote any current hero and promote the new one
// in a single D1 batch (D1 has no transactions; see CLAUDE.md).
//
// Validates the target project exists and is published before mutating.
// Returns the new {hero} so the UI can refresh without a follow-up GET.
const heroSchema = z.object({
projectId: z.string().min(1).nullable(),
});
homePage.put("/hero", async (c) => {
try {
requireUser(c.get("user"));
const dal = c.get("dal");
const db = getDb(c.env.DB);
const parsed = heroSchema.safeParse(await c.req.json());
if (!parsed.success) {
return c.json(
{ success: false, error: { message: "projectId must be a non-empty string or null" } },
400,
);
}
const { projectId } = parsed.data;
if (projectId === null) {
await db
.update(schema.projects)
.set({ isHero: false })
.where(eq(schema.projects.isHero, true));
} else {
const target = await dal.projects.findById(projectId);
if (!target) {
throw new NotFoundError("Project", projectId);
}
if (target.status !== "published") {
return c.json(
{
success: false,
error: { message: "Only published projects can be set as hero" },
},
409,
);
}
// D1 batch: demote any current hero + promote the target in one
// atomic call. Race-safe even if two admins click simultaneously.
await db.batch([
db
.update(schema.projects)
.set({ isHero: false })
.where(eq(schema.projects.isHero, true)),
db
.update(schema.projects)
.set({ isHero: true })
.where(eq(schema.projects.id, projectId)),
]);
}
invalidateHomepageCache(c);
// Return the updated hero (null when cleared, the target row otherwise)
// so the UI doesn't need a second round-trip.
const heroRow = projectId
? (
await db
.select()
.from(schema.projects)
.where(eq(schema.projects.id, projectId))
.limit(1)
)[0]
: null;
return success(c, { hero: heroRow ? summarize(heroRow) : null });
} catch (err) {
return handleError(c, err);
}
});
export default homePage;
|