post.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 updateObject: { [key: string]: string } = {};
  70. if (title) {
  71. updateObject["title"] = title;
  72. }
  73. if (content) {
  74. updateObject["content"] = content;
  75. }
  76. const newPost = update("Post", id, updateObject);
  77. if (newPost.length > 0) {
  78. return makeSuccessResponse(true);
  79. }
  80. }
  81. }
  82. return makeErrorResponse();
  83. },
  84. async DELETE(req: Request) {
  85. const reqJson = await req.json();
  86. const id = reqJson.id;
  87. const tokenUserId = checkToken(req);
  88. if (tokenUserId && id) {
  89. const flag = del("Post", {
  90. id,
  91. user_id: tokenUserId,
  92. });
  93. if (flag) {
  94. return makeSuccessResponse(true);
  95. }
  96. }
  97. return makeErrorResponse();
  98. },
  99. };