index.tsx 1.6 KB

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