website/src/routes/admin/announcements/+page.server.ts

51 lines
1.6 KiB
TypeScript
Raw Normal View History

import type { Actions } from "./$types";
import Joi from "joi";
import { fail } from "@sveltejs/kit";
2023-01-07 00:53:14 +05:30
import { db } from "$lib/server/db";
2023-01-10 19:43:53 +05:30
export const actions: Actions = {
2023-01-06 02:18:20 +05:30
add: async ({ request, locals }) => {
if (!await locals.getSession()) {
return fail(401, { addError: true, addMessage: "You must be logged in to post an announcement." });
} else {
2023-01-06 02:18:20 +05:30
const formData = await request.formData();
const BodyTypeSchema = Joi.object({
title: Joi.string().required(),
severity: Joi.string().required(),
author: Joi.string().required(),
link: Joi.string().optional().allow("")
});
if (BodyTypeSchema.validate(Object.fromEntries(formData.entries())).error) {
return fail(400, { addError: true, addMessage: String(BodyTypeSchema.validate(Object.fromEntries(formData.entries())).error) });
} else {
const now = Math.floor(Date.now() / 1000);
const data = {
...Object.fromEntries(formData.entries()),
2023-01-10 19:43:53 +05:30
created: now
2023-01-06 02:18:20 +05:30
};
2023-01-10 19:43:53 +05:30
2023-01-10 21:25:41 +05:30
const collection = db.collection("announcements");
2023-01-10 19:43:53 +05:30
await collection.deleteMany({});
2023-01-06 02:18:20 +05:30
2023-01-10 19:43:53 +05:30
await collection.insertOne(data);
2023-01-06 02:18:20 +05:30
return { addSuccess: true, addMessage: "Your announcement has been posted." };
}
}
2023-01-06 02:18:20 +05:30
},
2023-01-06 02:18:20 +05:30
delete: async ({ locals }) => {
if (!await locals.getSession()) {
return fail(401, { deleteError: true, deleteMessage: "You must be logged in to delete an announcement." });
} else {
2023-01-10 21:25:41 +05:30
const collection = db.collection("announcements");
2023-01-10 19:43:53 +05:30
await collection.deleteMany({});
2023-01-06 02:18:20 +05:30
return { deleteSuccess: true, deleteMessage: "Your announcement has been deleted." };
}
}
}