feat: finalize academy redesign and production readiness
Align admin, community, search, library, learning and course management with the mockup. Add saved courses, download history, public community feed, instructor directory, backend search, course views, admin content tools and community moderation. Harden API and Nginx for production.
This commit is contained in:
@@ -12,9 +12,12 @@ import { adminRoutes } from './routes/admin.js';
|
||||
import { mediaRoutes } from './routes/media.js';
|
||||
import { bunnyWebhookRoutes } from './routes/bunny-webhooks.js';
|
||||
import { profileRoutes } from './routes/profiles.js';
|
||||
import { savedCourseRoutes } from './routes/saved-courses.js';
|
||||
import { downloadRoutes } from './routes/downloads.js';
|
||||
import { searchRoutes } from './routes/search.js';
|
||||
|
||||
export function buildApp() {
|
||||
const app = Fastify({ logger: true });
|
||||
const app = Fastify({ logger: true, trustProxy: true });
|
||||
|
||||
// Bunny signs the exact webhook byte sequence. Preserve the raw JSON body
|
||||
// before parsing it so the signature can be verified server-side.
|
||||
@@ -80,6 +83,9 @@ export function buildApp() {
|
||||
app.register(authRoutes, { prefix: '/api/v1/auth' });
|
||||
app.register(profileRoutes, { prefix: '/api/v1/profiles' });
|
||||
app.register(courseRoutes, { prefix: '/api/v1/courses' });
|
||||
app.register(savedCourseRoutes, { prefix: '/api/v1/saved-courses' });
|
||||
app.register(downloadRoutes, { prefix: '/api/v1/downloads' });
|
||||
app.register(searchRoutes, { prefix: '/api/v1/search' });
|
||||
app.register(manageCourseRoutes, { prefix: '/api/v1/manage/courses' });
|
||||
app.register(mediaRoutes, { prefix: '/api/v1/manage/media' });
|
||||
app.register(bunnyWebhookRoutes, { prefix: '/api/v1/webhooks' });
|
||||
|
||||
@@ -12,7 +12,7 @@ const environmentSchema = z.object({
|
||||
JWT_SECRET: z.string().min(32).default('development-only-secret-change-before-production'),
|
||||
SUPERADMIN_EMAIL: optionalEnvironmentValue(z.string().email()),
|
||||
SUPERADMIN_PASSWORD: optionalEnvironmentValue(z.string().min(8)),
|
||||
SUPERADMIN_NAME: z.string().min(1).max(120).default('Compor HUB Superadmin'),
|
||||
SUPERADMIN_NAME: z.string().min(1).max(120).default('Compor HUB Admin'),
|
||||
AUTH_RATE_LIMIT_MAX: z.coerce.number().int().min(1).max(1000).default(10),
|
||||
AUTH_RATE_LIMIT_WINDOW_SECONDS: z.coerce.number().int().min(60).max(86_400).default(900),
|
||||
JWT_SESSION_TTL: z.string().regex(/^\d+[smhd]$/).default('7d'),
|
||||
|
||||
@@ -122,7 +122,8 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/users', adminAccess, async () => {
|
||||
const result = await pool.query(
|
||||
`select id, email, display_name as name, role, is_active as "isActive",
|
||||
created_at as "createdAt"
|
||||
created_at as "createdAt",
|
||||
(select max(lp.updated_at) from lesson_progress lp where lp.user_id = users.id) as "lastAccessAt"
|
||||
from users
|
||||
order by created_at desc`,
|
||||
);
|
||||
@@ -136,7 +137,9 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
(select count(*)::int from users where is_active) as "activeUsers",
|
||||
(select count(*)::int from courses where status = 'published') as "publishedCourses",
|
||||
(select count(*)::int from lesson_progress where completed_at is not null) as "completedLessons",
|
||||
(select count(*)::int from comments) as "comments"`,
|
||||
(select count(*)::int from comments) as "comments",
|
||||
(select count(*)::int from account_access_tokens
|
||||
where purpose = 'invitation' and used_at is null and expires_at > now()) as "pendingInvitations"`,
|
||||
);
|
||||
return { data: result.rows[0] };
|
||||
});
|
||||
@@ -370,7 +373,7 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
[input.email, input.role, hashToken(rawToken), config.INVITATION_TTL_HOURS, request.user.id],
|
||||
);
|
||||
await recordAudit({ actorId: request.user.id, action: 'invitation.created', subjectType: 'invitation', metadata: { email: input.email, role: input.role }, ipAddress: request.ip });
|
||||
return reply.code(201).send({ data: { inviteUrl: `${config.FRONTEND_ORIGIN}/#/invite?token=${rawToken}` } });
|
||||
return reply.code(201).send({ data: { inviteUrl: `${config.FRONTEND_ORIGIN}/invite?token=${rawToken}` } });
|
||||
});
|
||||
|
||||
app.post('/users/:userId/password-reset', adminAccess, async (request, reply) => {
|
||||
@@ -384,7 +387,7 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
[account.rows[0].email, account.rows[0].role, hashToken(rawToken), config.PASSWORD_RESET_TTL_HOURS, request.user.id],
|
||||
);
|
||||
await recordAudit({ actorId: request.user.id, action: 'password_reset.created', subjectType: 'user', subjectId: userId, metadata: { email: account.rows[0].email }, ipAddress: request.ip });
|
||||
return { data: { resetUrl: `${config.FRONTEND_ORIGIN}/#/reset-password?token=${rawToken}` } };
|
||||
return { data: { resetUrl: `${config.FRONTEND_ORIGIN}/reset-password?token=${rawToken}` } };
|
||||
});
|
||||
|
||||
app.patch('/users/:userId', adminAccess, async (request, reply) => {
|
||||
@@ -392,7 +395,7 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
const input = updateUserSchema.parse(request.body);
|
||||
|
||||
if (userId === request.user.id && (input.role !== undefined && input.role !== 'admin' || input.isActive === false)) {
|
||||
return reply.code(400).send({ error: 'Você não pode remover seu próprio acesso de superadmin.' });
|
||||
return reply.code(400).send({ error: 'Você não pode remover seu próprio acesso de admin.' });
|
||||
}
|
||||
if (input.email) {
|
||||
const duplicate = await pool.query('select 1 from users where email = $1 and id <> $2', [input.email, userId]);
|
||||
@@ -406,7 +409,8 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
role = coalesce($4::user_role, role),
|
||||
is_active = coalesce($5, is_active)
|
||||
where id = $1
|
||||
returning id, email, display_name as name, role, is_active as "isActive", created_at as "createdAt"`,
|
||||
returning id, email, display_name as name, role, is_active as "isActive", created_at as "createdAt",
|
||||
(select max(lp.updated_at) from lesson_progress lp where lp.user_id = users.id) as "lastAccessAt"`,
|
||||
[userId, input.name ?? null, input.email ?? null, input.role ?? null, input.isActive ?? null],
|
||||
);
|
||||
const account = result.rows[0];
|
||||
@@ -417,7 +421,7 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
|
||||
app.delete('/users/:userId', adminAccess, async (request, reply) => {
|
||||
const { userId } = userParamsSchema.parse(request.params);
|
||||
if (userId === request.user.id) return reply.code(400).send({ error: 'Você não pode excluir sua própria conta de superadmin.' });
|
||||
if (userId === request.user.id) return reply.code(400).send({ error: 'Você não pode excluir sua própria conta de admin.' });
|
||||
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
@@ -431,7 +435,7 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
|
||||
const admins = await client.query<{ count: string }>("select count(*) from users where role = 'admin' and is_active");
|
||||
if (Number(admins.rows[0].count) <= 1) {
|
||||
await client.query('rollback');
|
||||
return reply.code(400).send({ error: 'O último superadmin ativo não pode ser excluído.' });
|
||||
return reply.code(400).send({ error: 'O último admin ativo não pode ser excluído.' });
|
||||
}
|
||||
}
|
||||
// Courses remain available. Their ownership is transferred to the admin
|
||||
|
||||
@@ -31,6 +31,9 @@ export const courseSelect = (publicOnly = false, includeUnreadyMedia = false) =>
|
||||
c.cover_image_position_y as "coverImagePositionY",
|
||||
c.status,
|
||||
c.published_at as "publishedAt",
|
||||
c.updated_at as "updatedAt",
|
||||
c.created_at as "createdAt",
|
||||
c.view_count as views,
|
||||
jsonb_build_object(
|
||||
'id', u.id,
|
||||
'name', u.display_name
|
||||
@@ -96,15 +99,15 @@ export const courseSelect = (publicOnly = false, includeUnreadyMedia = false) =>
|
||||
join users u on u.id = c.instructor_id
|
||||
`;
|
||||
|
||||
export const courseRoutes: FastifyPluginAsync = async (app) => {
|
||||
const withoutProtectedMedia = (course: Record<string, unknown>) => ({
|
||||
...course,
|
||||
assets: [],
|
||||
lessons: Array.isArray(course.lessons)
|
||||
? course.lessons.map((lesson) => ({ ...lesson, media: [], assets: [] }))
|
||||
: [],
|
||||
});
|
||||
export const withoutProtectedMedia = (course: Record<string, unknown>) => ({
|
||||
...course,
|
||||
assets: [],
|
||||
lessons: Array.isArray(course.lessons)
|
||||
? course.lessons.map((lesson) => ({ ...lesson, media: [], assets: [] }))
|
||||
: [],
|
||||
});
|
||||
|
||||
export const courseRoutes: FastifyPluginAsync = async (app) => {
|
||||
const hasSession = async (request: { jwtVerify: () => Promise<unknown> }) => {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
@@ -166,21 +169,43 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
|
||||
|
||||
app.get('/', async (request) => {
|
||||
const authenticated = await hasSession(request);
|
||||
// Guests receive the published catalogue without protected media. Signed-in
|
||||
// learners also receive their own progress directly on each course so the
|
||||
// home screen can show "Continue assistindo" without extra requests.
|
||||
const catalogue = `
|
||||
${courseSelect()}
|
||||
left join platform_settings featured_setting on featured_setting.key = 'home.featuredCourseId'
|
||||
left join platform_settings order_setting on order_setting.key = 'home.courseOrder'
|
||||
where c.status = 'published'
|
||||
order by
|
||||
case when c.id::text = coalesce(featured_setting.value #>> '{}', '') then 0 else 1 end,
|
||||
coalesce((
|
||||
select position::int
|
||||
from jsonb_array_elements_text(coalesce(order_setting.value, '[]'::jsonb)) with ordinality as ordered(id, position)
|
||||
where ordered.id = c.id::text
|
||||
), 999999),
|
||||
c.published_at desc`;
|
||||
|
||||
if (!authenticated) {
|
||||
const result = await pool.query(catalogue);
|
||||
return { data: result.rows.map(withoutProtectedMedia) };
|
||||
}
|
||||
|
||||
const result = await pool.query(
|
||||
`${courseSelect()}
|
||||
left join platform_settings featured_setting on featured_setting.key = 'home.featuredCourseId'
|
||||
left join platform_settings order_setting on order_setting.key = 'home.courseOrder'
|
||||
where c.status = 'published'
|
||||
order by
|
||||
case when c.id::text = coalesce(featured_setting.value #>> '{}', '') then 0 else 1 end,
|
||||
coalesce((
|
||||
select position::int
|
||||
from jsonb_array_elements_text(coalesce(order_setting.value, '[]'::jsonb)) with ordinality as ordered(id, position)
|
||||
where ordered.id = c.id::text
|
||||
), 999999),
|
||||
c.published_at desc`,
|
||||
`select base.*, coalesce(progress.progress, 0)::int as progress, progress."lastActivity"
|
||||
from (${catalogue}) base
|
||||
left join lateral (
|
||||
select
|
||||
case when count(l.id) = 0 then 0
|
||||
else floor(100.0 * count(l.id) filter (where lp.completed_at is not null) / count(l.id))::int end as progress,
|
||||
max(lp.updated_at) as "lastActivity"
|
||||
from lessons l
|
||||
left join lesson_progress lp on lp.lesson_id = l.id and lp.user_id = $1
|
||||
where l.course_id = base.id
|
||||
) progress on true`,
|
||||
[request.user.id],
|
||||
);
|
||||
return { data: authenticated ? result.rows : result.rows.map(withoutProtectedMedia) };
|
||||
return { data: result.rows };
|
||||
});
|
||||
|
||||
// Paths intentionally reference existing courses instead of copying them.
|
||||
@@ -247,6 +272,19 @@ export const courseRoutes: FastifyPluginAsync = async (app) => {
|
||||
return { data: result.rows };
|
||||
});
|
||||
|
||||
app.post('/:courseId/view', { preHandler: app.authenticate }, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
const result = await pool.query<{ views: number }>(
|
||||
`update courses
|
||||
set view_count = view_count + 1
|
||||
where id = $1 and status = 'published'
|
||||
returning view_count as views`,
|
||||
[courseId],
|
||||
);
|
||||
if (!result.rows[0]) return reply.code(404).send({ error: 'Curso não encontrado.' });
|
||||
return { data: result.rows[0] };
|
||||
});
|
||||
|
||||
app.get('/:courseId', async (request, reply) => {
|
||||
const authenticated = await hasSession(request);
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
|
||||
52
server/src/routes/downloads.ts
Normal file
52
server/src/routes/downloads.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { pool } from '../db/pool.js';
|
||||
|
||||
const paramsSchema = z.object({ assetId: z.string().uuid() });
|
||||
|
||||
export const downloadRoutes: FastifyPluginAsync = async (app) => {
|
||||
const authenticated = { preHandler: app.authenticate };
|
||||
|
||||
app.get('/', authenticated, async (request) => {
|
||||
const result = await pool.query(
|
||||
`select a.id, a.name, a.kind, a.url, a.size_bytes as "sizeBytes",
|
||||
a.description, a.created_at as "createdAt",
|
||||
c.id as "courseId", c.title as "courseTitle",
|
||||
lesson.position as "lessonNumber",
|
||||
dh.downloaded_at as "downloadedAt"
|
||||
from download_history dh
|
||||
join assets a on a.id = dh.asset_id
|
||||
left join lessons lesson on lesson.id = a.lesson_id
|
||||
left join courses c on c.id = coalesce(a.course_id, lesson.course_id)
|
||||
where dh.user_id = $1
|
||||
order by dh.downloaded_at desc
|
||||
limit 200`,
|
||||
[request.user.id],
|
||||
);
|
||||
return { data: result.rows };
|
||||
});
|
||||
|
||||
app.post('/:assetId', authenticated, async (request, reply) => {
|
||||
const { assetId } = paramsSchema.parse(request.params);
|
||||
const result = await pool.query<{ course_status: string; instructor_id: string }>(
|
||||
`select c.status as course_status, c.instructor_id
|
||||
from assets a
|
||||
left join lessons lesson on lesson.id = a.lesson_id
|
||||
left join courses c on c.id = coalesce(a.course_id, lesson.course_id)
|
||||
where a.id = $1`,
|
||||
[assetId],
|
||||
);
|
||||
const asset = result.rows[0];
|
||||
if (!asset) return reply.code(404).send({ error: 'Material não encontrado.' });
|
||||
if (asset.course_status !== 'published' && request.user.role !== 'admin' && asset.instructor_id !== request.user.id) {
|
||||
return reply.code(404).send({ error: 'Material não encontrado.' });
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`insert into download_history (user_id, asset_id) values ($1, $2)
|
||||
on conflict (user_id, asset_id) do update set downloaded_at = now()`,
|
||||
[request.user.id, assetId],
|
||||
);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
};
|
||||
@@ -22,6 +22,10 @@ const commentSchema = z.object({
|
||||
});
|
||||
const commentParamsSchema = z.object({ commentId: z.string().uuid() });
|
||||
const replySchema = z.object({ text: z.string().trim().min(1).max(4000) });
|
||||
const communityQuerySchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
});
|
||||
|
||||
const ensurePublishedCourse = async (courseId: string) => {
|
||||
const result = await pool.query(
|
||||
@@ -38,6 +42,25 @@ const canViewCourseComments = async (courseId: string, user: { id: string; role:
|
||||
};
|
||||
|
||||
export const learningRoutes: FastifyPluginAsync = async (app) => {
|
||||
// Public, paginated feed used by the community screen. Individual course
|
||||
// threads remain authenticated because they are part of the lesson area.
|
||||
app.get('/community/comments', async (request) => {
|
||||
const { limit, offset } = communityQuerySchema.parse(request.query);
|
||||
const result = await pool.query(
|
||||
`select c.id, c.course_id as "courseId", c.lesson_id as "lessonId", c.body as text,
|
||||
c.created_at as "createdAt", u.display_name as "user",
|
||||
cr.body as reply, cr.created_at as "replyCreatedAt"
|
||||
from comments c
|
||||
join users u on u.id = c.author_id
|
||||
join courses co on co.id = c.course_id and co.status = 'published'
|
||||
left join comment_replies cr on cr.comment_id = c.id
|
||||
order by c.created_at desc
|
||||
limit $1 offset $2`,
|
||||
[limit, offset],
|
||||
);
|
||||
return { data: result.rows };
|
||||
});
|
||||
|
||||
const canModerateComment = async (commentId: string, user: { id: string; role: string }) => {
|
||||
const result = await pool.query<{ instructor_id: string }>(
|
||||
`select c.instructor_id
|
||||
|
||||
@@ -95,7 +95,7 @@ async function insertAssets(client: PoolClient, parent: { courseId?: string; les
|
||||
|
||||
async function assertActiveCategory(category: string) {
|
||||
const result = await pool.query('select 1 from course_categories where name = $1 and is_active', [category]);
|
||||
if (!result.rowCount) throw new CourseContentConflict('Selecione uma trilha ativa criada pelo superadmin.');
|
||||
if (!result.rowCount) throw new CourseContentConflict('Selecione uma trilha ativa criada pelo admin.');
|
||||
}
|
||||
|
||||
function assertPublishable(input: CourseInput) {
|
||||
@@ -185,8 +185,18 @@ export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
|
||||
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(false, true)} ${filters.sql}`, filters.values);
|
||||
return { data: result.rows };
|
||||
const withLearners = await pool.query(
|
||||
`select base.*, coalesce((
|
||||
select count(distinct lp.user_id)
|
||||
from lessons l
|
||||
join lesson_progress lp on lp.lesson_id = l.id
|
||||
where l.course_id = base.id
|
||||
), 0)::int as learners
|
||||
from (${courseSelect(false, true)} ${filters.sql}) base
|
||||
order by base."createdAt" desc`,
|
||||
filters.values,
|
||||
);
|
||||
return { data: withLearners.rows };
|
||||
});
|
||||
|
||||
app.get('/analytics', manageAccess, async (request) => {
|
||||
@@ -197,7 +207,10 @@ export const manageCourseRoutes: FastifyPluginAsync = async (app) => {
|
||||
count(distinct l.id)::int as "lessons",
|
||||
count(distinct lp.user_id)::int as "learners",
|
||||
count(distinct lp.lesson_id) filter (where lp.completed_at is not null)::int as "completedLessons",
|
||||
count(distinct cm.id)::int as "comments"
|
||||
count(distinct cm.id)::int as "comments",
|
||||
count(distinct cm.id) filter (where not exists (
|
||||
select 1 from comment_replies cr where cr.comment_id = cm.id
|
||||
))::int as "unansweredComments"
|
||||
from courses c
|
||||
left join lessons l on l.course_id = c.id
|
||||
left join lesson_progress lp on lp.lesson_id = l.id
|
||||
|
||||
@@ -6,6 +6,9 @@ import { courseSelect } from './courses.js';
|
||||
|
||||
const profileParamsSchema = z.object({ profileId: z.string().uuid() });
|
||||
const instructorParamsSchema = z.object({ instructorId: z.string().uuid() });
|
||||
const instructorListSchema = z.object({
|
||||
q: z.string().trim().max(120).optional().default(''),
|
||||
});
|
||||
|
||||
const optionalUrl = z.union([z.string().url().max(500), z.literal(''), z.null()]).optional()
|
||||
.transform((value) => value || null);
|
||||
@@ -124,6 +127,24 @@ export const profileRoutes: FastifyPluginAsync = async (app) => {
|
||||
return getPublicProfile(profileId, reply);
|
||||
});
|
||||
|
||||
app.get('/instructors', async (request) => {
|
||||
const { q } = instructorListSchema.parse(request.query);
|
||||
const result = await pool.query(
|
||||
`select u.id, u.display_name as name, u.role,
|
||||
u.avatar_image_url as "avatarImageUrl",
|
||||
u.profile_headline as headline,
|
||||
(select count(*)::int from courses c
|
||||
where c.instructor_id = u.id and c.status = 'published') as "courseCount"
|
||||
from users u
|
||||
where u.profile_is_public and u.is_active
|
||||
and u.role in ('instructor', 'admin')
|
||||
and ($1 = '' or u.display_name ilike $2 or u.profile_headline ilike $2)
|
||||
order by u.display_name`,
|
||||
[q, `%${q}%`],
|
||||
);
|
||||
return { data: result.rows };
|
||||
});
|
||||
|
||||
app.get('/instructors/:instructorId', async (request, reply) => {
|
||||
const { instructorId } = instructorParamsSchema.parse(request.params);
|
||||
return getPublicProfile(instructorId, reply, true);
|
||||
|
||||
40
server/src/routes/saved-courses.ts
Normal file
40
server/src/routes/saved-courses.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { pool } from '../db/pool.js';
|
||||
|
||||
const paramsSchema = z.object({ courseId: z.string().uuid() });
|
||||
|
||||
export const savedCourseRoutes: FastifyPluginAsync = async (app) => {
|
||||
const authenticated = { preHandler: app.authenticate };
|
||||
|
||||
app.get('/', authenticated, async (request) => {
|
||||
const result = await pool.query<{ courseId: string; createdAt: string }>(
|
||||
`select sc.course_id as "courseId", sc.created_at as "createdAt"
|
||||
from saved_courses sc
|
||||
join courses c on c.id = sc.course_id and c.status = 'published'
|
||||
where sc.user_id = $1
|
||||
order by sc.created_at desc`,
|
||||
[request.user.id],
|
||||
);
|
||||
return { data: result.rows };
|
||||
});
|
||||
|
||||
app.put('/:courseId', authenticated, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
const course = await pool.query("select id from courses where id = $1 and status = 'published'", [courseId]);
|
||||
if (!course.rowCount) return reply.code(404).send({ error: 'Curso não encontrado.' });
|
||||
|
||||
await pool.query(
|
||||
`insert into saved_courses (user_id, course_id) values ($1, $2)
|
||||
on conflict (user_id, course_id) do nothing`,
|
||||
[request.user.id, courseId],
|
||||
);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.delete('/:courseId', authenticated, async (request, reply) => {
|
||||
const { courseId } = paramsSchema.parse(request.params);
|
||||
await pool.query('delete from saved_courses where user_id = $1 and course_id = $2', [request.user.id, courseId]);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
};
|
||||
76
server/src/routes/search.ts
Normal file
76
server/src/routes/search.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import { pool } from '../db/pool.js';
|
||||
import { courseSelect, withoutProtectedMedia } from './courses.js';
|
||||
|
||||
const searchSchema = z.object({
|
||||
q: z.string().trim().max(120).optional().default(''),
|
||||
area: z.string().trim().max(120).optional().default(''),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||
});
|
||||
|
||||
export const searchRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/', async (request) => {
|
||||
const { q, area, limit } = searchSchema.parse(request.query);
|
||||
const term = `%${q}%`;
|
||||
|
||||
const [courses, paths, professors] = await Promise.all([
|
||||
pool.query(
|
||||
`${courseSelect()}
|
||||
where c.status = 'published'
|
||||
and ($1 = '' or c.title ilike $2 or c.description ilike $2 or c.category ilike $2 or u.display_name ilike $2)
|
||||
and ($3 = '' or c.category = $3)
|
||||
order by c.published_at desc
|
||||
limit $4`,
|
||||
[q, term, area, limit],
|
||||
),
|
||||
pool.query(
|
||||
`select
|
||||
p.id, p.title, p.description,
|
||||
coalesce(p.cover_image_url, (
|
||||
select value #>> '{}' from platform_settings where key = 'media.defaultCoverImageUrl'
|
||||
)) as "coverImageUrl",
|
||||
p.cover_image_zoom as "coverImageZoom",
|
||||
p.cover_image_position_x as "coverImagePositionX",
|
||||
p.cover_image_position_y as "coverImagePositionY",
|
||||
coalesce(jsonb_agg(jsonb_build_object(
|
||||
'id', c.id, 'title', c.title, 'category', c.category,
|
||||
'coverImageUrl', coalesce(c.cover_image_url, (
|
||||
select value #>> '{}' from platform_settings where key = 'media.defaultCoverImageUrl'
|
||||
)), 'position', pc.position
|
||||
) order by pc.position) filter (where c.id is not null), '[]'::jsonb) as courses
|
||||
from learning_paths p
|
||||
join learning_path_courses pc on pc.learning_path_id = p.id
|
||||
join courses c on c.id = pc.course_id and c.status = 'published'
|
||||
where p.status = 'published'
|
||||
and ($1 = '' or p.title ilike $2 or p.description ilike $2)
|
||||
group by p.id
|
||||
order by p.published_at desc
|
||||
limit $3`,
|
||||
[q, term, limit],
|
||||
),
|
||||
pool.query(
|
||||
`select u.id, u.display_name as name, u.role,
|
||||
u.avatar_image_url as "avatarImageUrl",
|
||||
u.profile_headline as headline,
|
||||
(select count(*)::int from courses c
|
||||
where c.instructor_id = u.id and c.status = 'published') as "courseCount"
|
||||
from users u
|
||||
where u.profile_is_public and u.is_active
|
||||
and u.role in ('instructor', 'admin')
|
||||
and ($1 = '' or u.display_name ilike $2 or u.profile_headline ilike $2)
|
||||
order by u.display_name
|
||||
limit $3`,
|
||||
[q, term, limit],
|
||||
),
|
||||
]);
|
||||
|
||||
return {
|
||||
data: {
|
||||
courses: courses.rows.map(withoutProtectedMedia),
|
||||
paths: paths.rows,
|
||||
professors: professors.rows,
|
||||
},
|
||||
};
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user