post.tsx 2.4 KB

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