All files / routes/admin social-studio-music.routes.ts

100% Statements 77/77
92.3% Branches 36/39
100% Functions 4/4
100% Lines 77/77

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                                                            1x     1x 9x 9x 9x 9x   9x   9x 6x         1x       5x               8x 8x     8x                 8x   1x         1x 14x 14x 14x   14x 14x 14x 14x   14x 2x   12x 1x   11x         1x       10x         2x   8x 1x     7x         7x 7x 14x     14x 6x         6x                       6x   8x         1x 7x 7x 7x 7x             7x         7x 1x     6x 6x 2x 1x   1x   5x 2x         1x       1x   4x 1x     4x 1x     3x           3x   3x         1x 2x 2x 2x   2x         2x 1x     1x         1x   1x          
// Admin Social Studio Music Track Management Routes
 
import { and, asc, eq, type SQL } from "drizzle-orm";
import { Hono } from "hono";
import type { Dal } from "../../dal";
import { getDb } from "../../db";
import {
	MUSIC_TRACK_CATEGORIES,
	socialStudioMusicTracks,
} from "../../db/schema";
import { NotFoundError, ValidationError } from "../../lib/errors";
import {
	ALLOWED_AUDIO_TYPES,
	MAX_AUDIO_SIZE,
	validateUploadedFile,
} from "../../lib/file-validation";
import { handleError, success } from "../../lib/response";
import { generateId } 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 socialStudioMusic = new Hono<Env>();
 
// GET /music-tracks — list all tracks (optionally filter by category, include inactive)
socialStudioMusic.get("/music-tracks", 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) {
			if (
				!MUSIC_TRACK_CATEGORIES.includes(
					category as (typeof MUSIC_TRACK_CATEGORIES)[number],
				)
			) {
				throw new ValidationError(
					`Invalid category. Allowed: ${MUSIC_TRACK_CATEGORIES.join(", ")}`,
				);
			}
			conditions.push(
				eq(
					socialStudioMusicTracks.category,
					category as (typeof MUSIC_TRACK_CATEGORIES)[number],
				),
			);
		}
 
		Eif (!includeInactive) {
			conditions.push(eq(socialStudioMusicTracks.isActive, true));
		}
 
		const tracks = await db
			.select()
			.from(socialStudioMusicTracks)
			.where(conditions.length > 0 ? and(...conditions) : undefined)
			.orderBy(
				asc(socialStudioMusicTracks.category),
				asc(socialStudioMusicTracks.name),
			);
 
		return success(c, { tracks });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// POST /music-tracks — create track with audio file upload to R2
socialStudioMusic.post("/music-tracks", async (c) => {
	try {
		const db = getDb(c.env.DB);
		const formData = await c.req.formData();
 
		const name = formData.get("name") as string | null;
		const category = formData.get("category") as string | null;
		const durationS = formData.get("durationS") as string | null;
		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 (
			!MUSIC_TRACK_CATEGORIES.includes(
				category as (typeof MUSIC_TRACK_CATEGORIES)[number],
			)
		) {
			throw new ValidationError(
				`Invalid category. Allowed: ${MUSIC_TRACK_CATEGORIES.join(", ")}`,
			);
		}
		if (
			!durationS ||
			Number.isNaN(Number(durationS)) ||
			Number(durationS) <= 0
		) {
			throw new ValidationError("Duration must be a positive number");
		}
		if (!file) {
			throw new ValidationError("Audio file is required");
		}
 
		validateUploadedFile(file, {
			allowedTypes: ALLOWED_AUDIO_TYPES,
			maxSize: MAX_AUDIO_SIZE,
		});
 
		const id = generateId();
		const ext = file.name.split(".").pop() || "mp3";
		const r2Key = `social-studio/music/${id}.${ext}`;
 
		// Upload to R2
		const arrayBuffer = await file.arrayBuffer();
		await c.env.R2.put(r2Key, arrayBuffer, {
			httpMetadata: { contentType: file.type },
		});
 
		// Insert record
		const [track] = await db
			.insert(socialStudioMusicTracks)
			.values({
				id,
				name: name.trim(),
				category: category as (typeof MUSIC_TRACK_CATEGORIES)[number],
				durationS: Number(durationS),
				r2Key,
				isActive: true,
			})
			.returning();
 
		return success(c, { track }, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// PUT /music-tracks/:id — update track metadata
socialStudioMusic.put("/music-tracks/:id", async (c) => {
	try {
		const db = getDb(c.env.DB);
		const id = c.req.param("id");
		const body = await c.req.json<{
			name?: string;
			category?: string;
			isActive?: boolean;
		}>();
 
		// Check track exists
		const [existing] = await db
			.select()
			.from(socialStudioMusicTracks)
			.where(eq(socialStudioMusicTracks.id, id));
 
		if (!existing) {
			throw new NotFoundError("Music track not found");
		}
 
		const updates: Record<string, unknown> = {};
		if (body.name !== undefined) {
			if (!body.name.trim()) {
				throw new ValidationError("Name cannot be empty");
			}
			updates.name = body.name.trim();
		}
		if (body.category !== undefined) {
			if (
				!MUSIC_TRACK_CATEGORIES.includes(
					body.category as (typeof MUSIC_TRACK_CATEGORIES)[number],
				)
			) {
				throw new ValidationError(
					`Invalid category. Allowed: ${MUSIC_TRACK_CATEGORIES.join(", ")}`,
				);
			}
			updates.category = body.category;
		}
		if (body.isActive !== undefined) {
			updates.isActive = body.isActive;
		}
 
		if (Object.keys(updates).length === 0) {
			return success(c, { track: existing });
		}
 
		const [track] = await db
			.update(socialStudioMusicTracks)
			.set(updates)
			.where(eq(socialStudioMusicTracks.id, id))
			.returning();
 
		return success(c, { track });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// DELETE /music-tracks/:id — soft delete (set isActive = false)
socialStudioMusic.delete("/music-tracks/:id", async (c) => {
	try {
		const db = getDb(c.env.DB);
		const id = c.req.param("id");
 
		const [existing] = await db
			.select()
			.from(socialStudioMusicTracks)
			.where(eq(socialStudioMusicTracks.id, id));
 
		if (!existing) {
			throw new NotFoundError("Music track not found");
		}
 
		await db
			.update(socialStudioMusicTracks)
			.set({ isActive: false })
			.where(eq(socialStudioMusicTracks.id, id));
 
		return success(c, { ok: true });
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default socialStudioMusic;