forked from 409/chat-app-frontend
57 lines
1.2 KiB
TypeScript
57 lines
1.2 KiB
TypeScript
import { error, fail, redirect, type Actions } from '@sveltejs/kit';
|
|
import { PUBLIC_BACKEND_URL } from '$env/static/public';
|
|
import { AUTH_COOIKIE_NAME } from '$lib/auth';
|
|
import type { PageServerLoad } from './$types';
|
|
import type { IMessage } from '$lib/message.svelte';
|
|
|
|
export const load: PageServerLoad = async ({ fetch, cookies, parent }) => {
|
|
await parent();
|
|
|
|
const authToken = cookies.get(AUTH_COOIKIE_NAME);
|
|
|
|
if (!authToken) {
|
|
error(401);
|
|
}
|
|
|
|
const response = await fetch(`${PUBLIC_BACKEND_URL}/messages`, {
|
|
headers: {
|
|
authorization: `Bearer ${authToken}`
|
|
}
|
|
});
|
|
|
|
if (!response.ok) {
|
|
error(response.status);
|
|
}
|
|
|
|
const messages = (await response.json()) as IMessage[];
|
|
|
|
return {
|
|
messages
|
|
};
|
|
};
|
|
|
|
export const actions = {
|
|
'send-message': async ({ request, fetch, cookies }) => {
|
|
const authToken = cookies.get(AUTH_COOIKIE_NAME);
|
|
|
|
if (authToken == null) {
|
|
return fail(400);
|
|
}
|
|
|
|
const formData = await request.formData();
|
|
|
|
await fetch(`${PUBLIC_BACKEND_URL}/message`, {
|
|
method: 'POST',
|
|
headers: {
|
|
authorization: `Bearer ${authToken}`
|
|
},
|
|
body: formData
|
|
});
|
|
},
|
|
logout: async ({ cookies }) => {
|
|
cookies.delete(AUTH_COOIKIE_NAME, { path: '/' });
|
|
|
|
redirect(303, '/login');
|
|
}
|
|
} satisfies Actions;
|