post.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { Handlers } from "$fresh/server.ts";
  2. import {
  3. checkToken,
  4. makeErrorResponse,
  5. makeSuccessResponse,
  6. } from "utils/server.ts";
  7. import { del, find, insert, update } from "utils/db.ts";
  8. export const handler: Handlers = {
  9. async GET(req: Request) {
  10. const reqJson = await req.json();
  11. const id = reqJson.id;
  12. const tokenUserId = checkToken(req);
  13. if (id) {
  14. const post = find(
  15. "Post",
  16. tokenUserId
  17. ? {
  18. id,
  19. user_id: tokenUserId,
  20. }
  21. : {
  22. id,
  23. shared: true,
  24. },
  25. ["title", "content"]
  26. );
  27. if (post.length > 0) {
  28. return makeSuccessResponse({
  29. title: post[0][0] as string,
  30. content: post[0][1] as string,
  31. });
  32. }
  33. }
  34. return makeErrorResponse();
  35. },
  36. async POST(req: Request) {
  37. const reqJson = await req.json();
  38. const title = reqJson.title || "";
  39. const content = reqJson.content || "";
  40. const tokenUserId = checkToken(req);
  41. if (tokenUserId) {
  42. const post = insert("Post", {
  43. title,
  44. content,
  45. user_id: tokenUserId,
  46. shared: false,
  47. });
  48. if (post.length > 0) {
  49. return makeSuccessResponse(post[0][0] as string);
  50. }
  51. }
  52. return makeErrorResponse();
  53. },
  54. async PUT(req: Request) {
  55. const reqJson = await req.json();
  56. const id = reqJson.id;
  57. const title = reqJson.title;
  58. const content = reqJson.content;
  59. const tokenUserId = checkToken(req);
  60. if (tokenUserId && id && title && content) {
  61. const post = find("Post", {
  62. id,
  63. user_id: tokenUserId,
  64. });
  65. if (post.length > 0) {
  66. const newPost = update("Post", id, {
  67. title,
  68. content,
  69. });
  70. if (newPost.length > 0) {
  71. return makeSuccessResponse(true);
  72. }
  73. }
  74. }
  75. return makeErrorResponse();
  76. },
  77. async DELETE(req: Request) {
  78. const reqJson = await req.json();
  79. const id = reqJson.id;
  80. const tokenUserId = checkToken(req);
  81. if (tokenUserId && id) {
  82. const post = del("Post", {
  83. id,
  84. user_id: tokenUserId,
  85. });
  86. if (post.length > 0) {
  87. return makeSuccessResponse(true);
  88. }
  89. }
  90. return makeErrorResponse();
  91. },
  92. };