This commit is contained in:
188
server/src/routes/manage-courses.ts
Normal file
188
server/src/routes/manage-courses.ts
Normal file
@@ -0,0 +1,188 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import type { PoolClient } from 'pg';
|
||||
import { z } from 'zod';
|
||||
import { courseSelect } from './courses.js';
|
||||
import { pool } from '../db/pool.js';
|
||||
|
||||
const mediaSchema = z.object({
|
||||
provider: z.string().trim().min(1).max(80),
|
||||
externalId: z.string().trim().min(1).max(500),
|
||||
playbackUrl: z.string().url().nullable().optional(),
|
||||
embedUrl: z.string().url().nullable().optional(),
|
||||
status: z.enum(['processing', 'ready', 'failed']).default('ready'),
|
||||
durationSeconds: z.number().int().nonnegative().nullable().optional(),
|
||||
});
|
||||
|
||||
const assetSchema = z.object({
|
||||
name: z.string().trim().min(1).max(255),
|
||||
kind: z.enum(['document', 'spreadsheet', 'archive', 'image', 'link']),
|
||||
url: z.string().url(),
|
||||
description: z.string().max(2000).default(''),
|
||||
accessLevel: z.enum(['public', 'enrolled']).default('enrolled'),
|
||||
});
|
||||
|
||||
const lessonSchema = z.object({
|
||||
title: z.string().trim().min(1).max(255),
|
||||
description: z.string().max(5000).default(''),
|
||||
durationSeconds: z.number().int().nonnegative().nullable().optional(),
|
||||
accessLevel: z.enum(['public', 'enrolled']).default('enrolled'),
|
||||
media: z.array(mediaSchema).default([]),
|
||||
assets: z.array(assetSchema).default([]),
|
||||
});
|
||||
|
||||
const courseSchema = z.object({
|
||||
title: z.string().trim().min(1).max(255),
|
||||
slug: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).max(280).optional(),
|
||||
description: z.string().max(10000).default(''),
|
||||
category: z.string().trim().min(1).max(120),
|
||||
coverImageUrl: z.string().url().nullable().optional(),
|
||||
status: z.enum(['draft', 'published']).default('draft'),
|
||||
lessons: z.array(lessonSchema).min(1),
|
||||
assets: z.array(assetSchema).default([]),
|
||||
});
|
||||
|
||||
const paramsSchema = z.object({ courseId: z.string().uuid() });
|
||||
type CourseInput = z.infer<typeof courseSchema>;
|
||||
|
||||
function slugify(value: string) {
|
||||
return value
|
||||
.normalize('NFD')
|
||||
.replace(/[\u0300-\u036f]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/(^-|-$)/g, '') || 'course';
|
||||
}
|
||||
|
||||
async function uniqueSlug(client: PoolClient, requestedSlug: string | undefined, title: string, currentCourseId?: string) {
|
||||
const base = requestedSlug ?? slugify(title);
|
||||
let candidate = base;
|
||||
|
||||
while (true) {
|
||||
const result = await client.query(
|
||||
'select 1 from courses where slug = $1 and ($2::uuid is null or id <> $2::uuid)',
|
||||
[candidate, currentCourseId ?? null],
|
||||
);
|
||||
if (!result.rowCount) return candidate;
|
||||
candidate = `${base}-${randomUUID().slice(0, 8)}`;
|
||||
}
|
||||
}
|
||||
|
||||
async function insertAssets(client: PoolClient, parent: { courseId?: string; lessonId?: string }, assets: CourseInput['assets']) {
|
||||
for (const asset of assets) {
|
||||
await client.query(
|
||||
`insert into assets (course_id, lesson_id, name, kind, url, description, access_level)
|
||||
values ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
[parent.courseId ?? null, parent.lessonId ?? null, asset.name, asset.kind, asset.url, asset.description, asset.accessLevel],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function replaceCourseContents(client: PoolClient, courseId: string, input: CourseInput) {
|
||||
// This replacement strategy is safe before student progress exists. The next
|
||||
// iteration will switch to per-lesson updates to preserve historical progress.
|
||||
await client.query('delete from lessons where course_id = $1', [courseId]);
|
||||
await client.query('delete from assets where course_id = $1', [courseId]);
|
||||
|
||||
await insertAssets(client, { courseId }, input.assets);
|
||||
for (const [index, lesson] of input.lessons.entries()) {
|
||||
const lessonResult = await client.query<{ id: string }>(
|
||||
`insert into lessons (course_id, title, description, position, duration_seconds, access_level)
|
||||
values ($1, $2, $3, $4, $5, $6)
|
||||
returning id`,
|
||||
[courseId, lesson.title, lesson.description, index + 1, lesson.durationSeconds ?? null, lesson.accessLevel],
|
||||
);
|
||||
const lessonId = lessonResult.rows[0].id;
|
||||
|
||||
for (const media of lesson.media) {
|
||||
await client.query(
|
||||
`insert into lesson_media
|
||||
(lesson_id, provider, external_id, playback_url, embed_url, status, duration_seconds)
|
||||
values ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
[lessonId, media.provider, media.externalId, media.playbackUrl ?? null, media.embedUrl ?? null, media.status, media.durationSeconds ?? null],
|
||||
);
|
||||
}
|
||||
await insertAssets(client, { lessonId }, lesson.assets);
|
||||
}
|
||||
}
|
||||
|
||||
async function assertCanManageCourse(courseId: string, user: { id: string; role: string }) {
|
||||
const result = await pool.query<{ instructor_id: string }>('select instructor_id from courses where id = $1', [courseId]);
|
||||
const course = result.rows[0];
|
||||
if (!course) return { error: 'Course not found', statusCode: 404 as const };
|
||||
if (user.role !== 'admin' && course.instructor_id !== user.id) {
|
||||
return { error: 'You can only manage your own courses', statusCode: 403 as const };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
|
||||
const manageAccess = { preHandler: app.requireRoles(['instructor', 'admin']) };
|
||||
|
||||
app.get('/', manageAccess, async (request) => {
|
||||
const filters = request.user.role === 'admin'
|
||||
? { sql: "where c.status <> 'archived' order by c.created_at desc", values: [] as string[] }
|
||||
: { sql: "where c.instructor_id = $1 and c.status <> 'archived' order by c.created_at desc", values: [request.user.id] };
|
||||
const result = await pool.query(`${courseSelect()} ${filters.sql}`, filters.values);
|
||||
return { data: result.rows };
|
||||
});
|
||||
|
||||
app.post('/', manageAccess, async (request, reply) => {
|
||||
const input = courseSchema.parse(request.body);
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('begin');
|
||||
const slug = await uniqueSlug(client, input.slug, input.title);
|
||||
const course = await client.query<{ id: string }>(
|
||||
`insert into courses (slug, title, description, category, cover_image_url, status, instructor_id, published_at)
|
||||
values ($1, $2, $3, $4, $5, $6::course_status, $7, case when $6::course_status = 'published'::course_status then now() else null end)
|
||||
returning id`,
|
||||
[slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.status, request.user.id],
|
||||
);
|
||||
await replaceCourseContents(client, course.rows[0].id, input);
|
||||
await client.query('commit');
|
||||
return reply.code(201).send({ data: { id: course.rows[0].id } });
|
||||
} catch (error) {
|
||||
await client.query('rollback');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
|
||||
app.patch('/:courseId', manageAccess, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
const input = courseSchema.parse(request.body);
|
||||
const accessError = await assertCanManageCourse(courseId, request.user);
|
||||
if (accessError) return reply.code(accessError.statusCode).send({ error: accessError.error });
|
||||
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('begin');
|
||||
const slug = await uniqueSlug(client, input.slug, input.title, courseId);
|
||||
await client.query(
|
||||
`update courses
|
||||
set slug = $2, title = $3, description = $4, category = $5, cover_image_url = $6,
|
||||
status = $7::course_status, published_at = case when $7::course_status = 'published'::course_status then coalesce(published_at, now()) else null end
|
||||
where id = $1`,
|
||||
[courseId, slug, input.title, input.description, input.category, input.coverImageUrl ?? null, input.status],
|
||||
);
|
||||
await replaceCourseContents(client, courseId, input);
|
||||
await client.query('commit');
|
||||
return { data: { id: courseId } };
|
||||
} catch (error) {
|
||||
await client.query('rollback');
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/:courseId', manageAccess, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
const accessError = await assertCanManageCourse(courseId, request.user);
|
||||
if (accessError) return reply.code(accessError.statusCode).send({ error: accessError.error });
|
||||
await pool.query(`update courses set status = 'archived', published_at = null where id = $1`, [courseId]);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user