post.tsx 2.4 KB

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