post.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { createDefine } from "fresh";
  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. const define = createDefine<Record<never, never>>();
  10. export const handler = define.handlers({
  11. async GET(ctx) {
  12. const req = ctx.req;
  13. const reqJson = await req.json();
  14. const id = reqJson.id;
  15. const tokenUserId = checkToken(req);
  16. if (id) {
  17. const post = find(
  18. "Post",
  19. tokenUserId
  20. ? { id, user_id: tokenUserId }
  21. : { id, shared: true },
  22. ["title", "content"],
  23. );
  24. if (post.length > 0) {
  25. return makeSuccessResponse({
  26. title: post[0][0] as string,
  27. content: post[0][1] as string,
  28. });
  29. }
  30. }
  31. return makeErrorResponse();
  32. },
  33. async POST(ctx) {
  34. const req = ctx.req;
  35. const reqJson = await req.json();
  36. const title = reqJson.title || "";
  37. const content = reqJson.content || "";
  38. const tokenUserId = checkToken(req);
  39. if (tokenUserId) {
  40. const postId = uid(12);
  41. const post = insert("Post", {
  42. id: postId,
  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(ctx) {
  55. const req = ctx.req;
  56. const reqJson = await req.json();
  57. const id = reqJson.id;
  58. const title = reqJson.title;
  59. const content = reqJson.content;
  60. const tokenUserId = checkToken(req);
  61. if (tokenUserId && id && (title || content)) {
  62. const post = find("Post", { id, user_id: tokenUserId });
  63. if (post.length > 0) {
  64. const updateObject: { [key: string]: string } = {};
  65. if (title) updateObject["title"] = title;
  66. if (content) updateObject["content"] = content;
  67. const newPost = update("Post", id, updateObject);
  68. if (newPost.length > 0) {
  69. return makeSuccessResponse(true);
  70. }
  71. }
  72. }
  73. return makeErrorResponse();
  74. },
  75. async DELETE(ctx) {
  76. const req = ctx.req;
  77. const reqJson = await req.json();
  78. const id = reqJson.id;
  79. const tokenUserId = checkToken(req);
  80. if (tokenUserId && id) {
  81. const flag = del("Post", { id, user_id: tokenUserId });
  82. if (flag) {
  83. return makeSuccessResponse(true);
  84. }
  85. }
  86. return makeErrorResponse();
  87. },
  88. });