aboutsummaryrefslogtreecommitdiffstats
path: root/website/src/routes/welcome/+page.server.ts
blob: 5a6e0246b2d194f850c824ebb60428f4d89c47f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { profileSchema } from '$lib/schemas/profile';

export const actions: Actions = {
  default: async ({ request, fetch }) => {
    console.log('hello');
    const formData = await request.formData();
    const data = Object.fromEntries(formData);

    const result = profileSchema.safeParse(data);

    if (!result.success) {
      return fail(400, {
        errors: result.error.flatten().fieldErrors,
        data: data as Record<string, string>,
      });
    }

    const response = await fetch(`/api/check-username?u=${result.data.username}`);
    const { available } = await response.json();

    if (!available) {
      return fail(400, {
        errors: { username: ['This username is already taken'] },
        data: data as Record<string, string>,
      });
    }

    // 3. Success: Send to backend to create profile
    // await fetch('...', { method: 'POST', body: JSON.stringify(result.data) });

    throw redirect(303, '/dashboard');
  },
};

export const load = async ({ fetch, request }) => {
  const res = await fetch('http://localhost:2210/me', {
    headers: {
      cookie: request.headers.get('cookie') || '',
    },
  });

  if (res.status === 401) throw redirect(302, '/login');

  const userData = await res.json();

  // if (userData.is_onboarded) {
  //     throw redirect(302, '/dashboard');
  // }
  //
  return {
    user: userData,
  };
};