Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/** @jsxImportSource https://esm.sh/hono@latest/jsx **/
import { getUserByUsername, updateUser, uploadProfileImage } from "https://esm.town/v/iamseeley/Queries";
import EditProfilePage from "https://esm.town/v/iamseeley/EditProfilePage";
import RootLayout from "https://esm.town/v/iamseeley/RootLayout";
export const getUserProfileHandler = async (c) => {
const username = c.req.param('username');
const payload = await c.get('jwtPayload');
if (payload.username !== username) {
return c.html(
<RootLayout>
<p>You are not authorized to access this profile.</p>
</RootLayout>
);
}
try {
const user = await getUserByUsername(username);
return c.html(<EditProfilePage user={user} />);
} catch (error) {
console.error("Error fetching user:", error);
return c.html(
<RootLayout>
<p>Error loading profile.</p>
</RootLayout>
);
}
};
export const updateUserProfileHandler = async (c) => {
try {
const body = await c.req.parseBody();
const username = c.req.param("username");
const name = body.name;
const bio = body.bio;
const city = body.city;
const currentlyListening = body.currentlyListening;
const currentlyReading = {
title: body.currentlyReadingTitle,
author: body.currentlyReadingAuthor,
coverImage: body.currentlyReadingCoverImage,
};
const currentlyWatching = {
title: body.currentlyWatchingTitle,
platform: body.currentlyWatchingPlatform,
posterImage: body.currentlyWatchingPosterImage,
};
const profile_theme = body.profile_theme;
if (typeof name !== "string" || typeof bio !== "string") {
throw new Error("name and bio must be strings.");
}
const existingUser = await getUserByUsername(username);
// Handle profile image upload
const profileImgFile = body.profile_img;
let profileImgUrl = existingUser.profile_img; // Default to existing image URL
if (profileImgFile && profileImgFile.size) {
profileImgUrl = await uploadProfileImage(profileImgFile, username);
}
await updateUser(existingUser.id, name, bio, city, currentlyListening, currentlyReading, currentlyWatching, profile_theme, profileImgUrl);
const updatedUser = await getUserByUsername(username);
return c.html(<EditProfilePage user={updatedUser} />);
} catch (error) {
console.error("Error updating profile:", error);
return c.html(
<RootLayout>
<p>Error updating profile.</p>
</RootLayout>
);
}
};
May 23, 2024