Files
base/src/routes/training/+page.server.ts
T

110 lines
2.6 KiB
TypeScript

import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
type TrainingVideo = {
id: string;
title: string;
description: string | null;
created: string;
videoUrl: string;
};
const VIDEO_COLLECTION = 'year';
const VIDEO_FIELD = 'Media';
export const load: PageServerLoad = async ({ locals }) => {
const user = locals.user;
let records: any[] = [];
try {
records = await locals.pb.collection(VIDEO_COLLECTION).getFullList({
sort: '-created'
});
} catch (e) {
console.error('Failed to load training videos from PocketBase', e);
records = [];
}
const videos: TrainingVideo[] = records.map((record: any) => {
const fileName = record[VIDEO_FIELD];
const videoUrl = fileName
? locals.pb.files.getUrl(record, fileName)
: '';
return {
id: record.id as string,
title: (record.title as string) ?? 'Untitled video',
description: (record.description as string) ?? null,
created: record.created as string,
videoUrl
};
});
const canUpload = Boolean(user?.training_admin);
return {
videos,
canUpload
};
};
export const actions: Actions = {
upload: async ({ request, locals }) => {
const user = locals.user;
if (!user) {
throw redirect(303, '/login');
}
if (!user.training_admin) {
return fail(403, {
error: 'You do not have permission to upload training videos.'
});
}
const formData = await request.formData();
const title = String(formData.get('title') ?? '').trim();
const description = String(formData.get('description') ?? '').trim();
const file = formData.get('video');
if (!title) {
return fail(400, {
error: 'Title is required.',
values: { title, description }
});
}
if (!(file instanceof File)) {
return fail(400, {
error: 'Please choose a video file to upload.',
values: { title, description }
});
}
const createData = new FormData();
createData.set('title', title);
if (description) {
createData.set('description', description);
}
createData.set(VIDEO_FIELD, file);
try {
await locals.pb.collection(VIDEO_COLLECTION).create(createData);
} catch (e) {
const message =
e && typeof e === 'object' && 'message' in e
? String((e as { message: string }).message)
: 'Could not upload video.';
return fail(500, {
error: message,
values: { title, description }
});
}
throw redirect(303, '/training');
}
};