index.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { Head } from "$fresh/runtime.ts";
  2. import { Handlers, PageProps } from "$fresh/server.ts";
  3. import { checkToken } from "utils/server.ts";
  4. import { find } from "utils/db.ts";
  5. import HomeBar from "../islands/HomeBar.tsx";
  6. import PostList from "../islands/PostList.tsx";
  7. interface HomeProps {
  8. name: string;
  9. list: { id: string; title: string; content: string; shared: boolean }[];
  10. }
  11. export const handler: Handlers<HomeProps> = {
  12. GET(req, ctx) {
  13. const tokenUserId = checkToken(req);
  14. if (tokenUserId) {
  15. const user = find(
  16. "User",
  17. {
  18. id: tokenUserId,
  19. },
  20. ["name"],
  21. );
  22. if (user.length > 0) {
  23. const posts = find("Post", { user_id: tokenUserId }, [
  24. "id",
  25. "title",
  26. "content",
  27. "shared",
  28. ]);
  29. return ctx.render({
  30. name: user[0][0] as string,
  31. list: posts.map((post) => ({
  32. id: post[0] as string,
  33. title: post[1] as string,
  34. content: post[2] as string,
  35. shared: post[3] as boolean,
  36. })),
  37. });
  38. }
  39. }
  40. // Redirect to login page if not valid
  41. const headers = new Headers();
  42. headers.set("location", "/login");
  43. return new Response(null, {
  44. status: 303, // See Other
  45. headers,
  46. });
  47. },
  48. };
  49. export default function Home(props: PageProps<HomeProps>) {
  50. return (
  51. <>
  52. <Head>
  53. <title>Home</title>
  54. </Head>
  55. <div className="pd-page">
  56. <HomeBar name={props.data.name} />
  57. <PostList posts={props.data.list} />
  58. </div>
  59. </>
  60. );
  61. }