FBLA25/src/routes/companies/[company]/edit/+page.server.ts
drake 77655c779d
All checks were successful
ci / docker_image (push) Successful in 1m37s
ci / deploy (push) Successful in 16s
import cleanup
2025-03-29 18:13:02 -05:00

70 lines
2.3 KiB
TypeScript

import { type Actions, error, fail, redirect } from '@sveltejs/kit';
import { deleteCompany, editCompany, getCompany } from '$lib/db/index.server';
import { PERMISSIONS } from '$lib/consts';
import { getUserPerms } from '$lib/index.server';
import type { PageServerLoad } from './$types';
import type { Company } from '$lib/types';
export const load: PageServerLoad = async ({ cookies, params }) => {
const id = parseInt(params.company);
const perms = getUserPerms(cookies);
if (perms >= 0 && (perms & PERMISSIONS.MANAGE_COMPANIES) > 0) {
return {
company: await getCompany(id)
};
}
error(403, 'Unauthorized');
};
export const actions: Actions = {
submit: async ({ request, cookies, params }) => {
const id = parseInt(params.company!);
const data = await request.formData();
const name = data.get('name')?.toString().trim();
let website = data.get('website')?.toString().trim();
const description = data.get('description')?.toString().trim();
const requestPerms = getUserPerms(cookies);
if (
!(
(requestPerms >= 0 && (requestPerms & PERMISSIONS.MANAGE_COMPANIES) > 0) ||
(requestPerms & PERMISSIONS.SUBMIT_POSTINGS) > 0
)
) {
return fail(403, { errorMessage: 'You cannot preform this action!' });
}
if (!name || name === '' || !website || website === '' || !description || description === '') {
return fail(400, { errorMessage: 'All fields are required' });
}
if (!website.includes('.')) {
return fail(400, { errorMessage: 'Invalid website' });
}
if (!website.startsWith('http://') && !website.startsWith('https://'))
website = `https://${website}`;
try {
await editCompany(<Company>{
id: id,
name: name,
website: website,
description: description
});
} catch (err) {
return fail(500, { errorMessage: `Internal Server Error: ${err}` });
}
redirect(301, `/companies/${id}`);
},
delete: async ({ cookies, params }) => {
const id = parseInt(params.company!);
const requestPerms = getUserPerms(cookies);
if (!(requestPerms >= 0 && (requestPerms & PERMISSIONS.MANAGE_COMPANIES) > 0)) {
return fail(403, { errorMessage: 'You cannot preform this action!' });
}
try {
await deleteCompany(id);
} catch (err) {
return fail(500, { errorMessage: `Internal Server Error: ${err}` });
}
}
};