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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | 1x 1x 7x 7x 7x 7x 7x 7x 2x 7x 6x 7x 6x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x 10x 1x 9x 1x 8x 8x 1x 7x 7x 1x 6x 6x 3x 3x 3x 3x 3x 1x 4x 4x 3x 9x 1x 18x 18x 18x 18x 18x 1x 17x 18x 18x 18x 3x 3x 3x 3x 2x 1x 14x 17x 17x 4x 4x 3x 16x 2x 16x 16x 3x 3x 3x 1x 2x 2x 1x 1x 14x 1x 14x 2x 14x 2x 14x 2x 2x 2x 2x 2x 1x 1x 13x 1x 12x 12x 11x 6x 1x 3x 3x 3x 3x 3x 1x 2x 1x 2x | // Admin Social Studio Template Management Routes
import { Hono } from "hono";
import { eq, and, asc, type SQL } from "drizzle-orm";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import { success, handleError } from "../../lib/response";
import { NotFoundError, ValidationError } from "../../lib/errors";
import { generateId } from "../../lib/utils";
import {
validateUploadedFile,
ALLOWED_IMAGE_TYPES,
MAX_IMAGE_SIZE,
} from "../../lib/file-validation";
import { validateTemplateSlots } from "../../lib/template-slots-validator";
import { socialStudioTemplates } from "../../db/schema";
import { getDb } from "../../db";
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
};
};
const socialStudioTemplatesRoutes = new Hono<Env>();
// GET /templates — list all templates (optionally filter by category, include inactive)
socialStudioTemplatesRoutes.get("/templates", async (c) => {
try {
const db = getDb(c.env.DB);
const category = c.req.query("category");
const includeInactive = c.req.query("includeInactive") === "true";
const conditions: SQL[] = [];
if (category) {
conditions.push(eq(socialStudioTemplates.category, category));
}
if (!includeInactive) {
conditions.push(eq(socialStudioTemplates.isActive, true));
}
const templates = await db
.select()
.from(socialStudioTemplates)
.where(conditions.length > 0 ? and(...conditions) : undefined)
.orderBy(
asc(socialStudioTemplates.category),
asc(socialStudioTemplates.name),
);
return success(c, { templates });
} catch (err) {
return handleError(c, err);
}
});
// POST /templates — create template with optional thumbnail upload to R2
socialStudioTemplatesRoutes.post("/templates", async (c) => {
try {
const db = getDb(c.env.DB);
const formData = await c.req.formData();
const name = formData.get("name") as string | null;
const description = formData.get("description") as string | null;
const category = formData.get("category") as string | null;
const slotsJson = formData.get("slots") as string | null;
const defaultMusicId = formData.get("defaultMusicId") as string | null;
const brandingRequired = formData.get("brandingRequired") === "true";
const file = formData.get("file") as File | null;
if (!name?.trim()) {
throw new ValidationError("Name is required");
}
if (!category) {
throw new ValidationError("Category is required");
}
if (!slotsJson) {
throw new ValidationError("Slots JSON is required");
}
// Parse and validate slots
let parsedSlots: unknown;
try {
parsedSlots = JSON.parse(slotsJson);
} catch {
throw new ValidationError("Slots must be valid JSON");
}
const validation = validateTemplateSlots(parsedSlots);
if (!validation.success) {
throw new ValidationError(`Invalid slots: ${validation.error}`);
}
// Upload thumbnail to R2 if provided
let thumbnailR2Key: string | null = null;
if (file) {
validateUploadedFile(file, {
allowedTypes: ALLOWED_IMAGE_TYPES,
maxSize: MAX_IMAGE_SIZE,
});
const id = generateId();
const ext = file.name.split(".").pop() || "png";
thumbnailR2Key = `social-studio/templates/${id}.${ext}`;
const arrayBuffer = await file.arrayBuffer();
await c.env.R2.put(thumbnailR2Key, arrayBuffer, {
httpMetadata: { contentType: file.type },
});
}
const id = generateId();
const [template] = await db
.insert(socialStudioTemplates)
.values({
id,
name: name.trim(),
description: description?.trim() || null,
category,
slots: slotsJson,
defaultMusicId: defaultMusicId || null,
brandingRequired,
thumbnailR2Key,
isSystem: false,
isActive: true,
})
.returning();
return success(c, { template }, 201);
} catch (err) {
return handleError(c, err);
}
});
// PUT /templates/:id — update template fields, optionally upload new thumbnail
socialStudioTemplatesRoutes.put("/templates/:id", async (c) => {
try {
const db = getDb(c.env.DB);
const id = c.req.param("id");
// Check template exists
const [existing] = await db
.select()
.from(socialStudioTemplates)
.where(eq(socialStudioTemplates.id, id));
if (!existing) {
throw new NotFoundError("Template not found");
}
const contentType = c.req.header("content-type") || "";
const isMultipart = contentType.includes("multipart/form-data");
let body: Record<string, unknown>;
let file: File | null = null;
if (isMultipart) {
const formData = await c.req.formData();
body = {};
for (const [key, value] of formData.entries()) {
if (key === "file" && value instanceof File) {
file = value;
} else {
body[key] = value;
}
}
} else {
body = await c.req.json();
}
const updates: Record<string, unknown> = {};
if (body.name !== undefined) {
const name = String(body.name).trim();
if (!name) throw new ValidationError("Name cannot be empty");
updates.name = name;
}
if (body.description !== undefined) {
updates.description = body.description ? String(body.description).trim() : null;
}
Iif (body.category !== undefined) {
updates.category = body.category;
}
if (body.slots !== undefined) {
const slotsJson = String(body.slots);
let parsedSlots: unknown;
try {
parsedSlots = JSON.parse(slotsJson);
} catch {
throw new ValidationError("Slots must be valid JSON");
}
const validation = validateTemplateSlots(parsedSlots);
if (!validation.success) {
throw new ValidationError(`Invalid slots: ${validation.error}`);
}
updates.slots = slotsJson;
}
if (body.defaultMusicId !== undefined) {
updates.defaultMusicId = body.defaultMusicId || null;
}
if (body.brandingRequired !== undefined) {
updates.brandingRequired = body.brandingRequired === "true" || body.brandingRequired === true;
}
if (body.isActive !== undefined) {
updates.isActive = body.isActive === "true" || body.isActive === true;
}
// Upload new thumbnail if provided
if (file) {
validateUploadedFile(file, {
allowedTypes: ALLOWED_IMAGE_TYPES,
maxSize: MAX_IMAGE_SIZE,
});
const fileId = generateId();
const ext = file.name.split(".").pop() || "png";
const thumbnailR2Key = `social-studio/templates/${fileId}.${ext}`;
const arrayBuffer = await file.arrayBuffer();
await c.env.R2.put(thumbnailR2Key, arrayBuffer, {
httpMetadata: { contentType: file.type },
});
updates.thumbnailR2Key = thumbnailR2Key;
}
if (Object.keys(updates).length === 0) {
return success(c, { template: existing });
}
updates.dateUpdated = new Date();
const [template] = await db
.update(socialStudioTemplates)
.set(updates)
.where(eq(socialStudioTemplates.id, id))
.returning();
return success(c, { template });
} catch (err) {
return handleError(c, err);
}
});
// DELETE /templates/:id — soft delete (set isActive = false)
socialStudioTemplatesRoutes.delete("/templates/:id", async (c) => {
try {
const db = getDb(c.env.DB);
const id = c.req.param("id");
const [existing] = await db
.select()
.from(socialStudioTemplates)
.where(eq(socialStudioTemplates.id, id));
if (!existing) {
throw new NotFoundError("Template not found");
}
await db
.update(socialStudioTemplates)
.set({ isActive: false })
.where(eq(socialStudioTemplates.id, id));
return success(c, { ok: true });
} catch (err) {
return handleError(c, err);
}
});
export default socialStudioTemplatesRoutes;
|