md.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { Request as ExpressRequest, Response as ExpressResponse } from "express";
  2. import { existsSync, promises } from "fs";
  3. import { join } from "path";
  4. import { ENVIRONMENT } from "src/utils/environment";
  5. import { Option } from "@shared/common/async_utils";
  6. import { rpcClient } from "src/utils/rpc";
  7. import { MDText } from "./md_interfaces";
  8. const FILE_PATH = join(ENVIRONMENT.dataPath, "rules.md");
  9. type GetResult = Promise<ExpressResponse<Option<MDText, { error: string }>>>;
  10. export const get = async (req: ExpressRequest, res: ExpressResponse): GetResult => {
  11. if (!existsSync(FILE_PATH)) {
  12. return res.json({
  13. ok: true,
  14. text: "",
  15. });
  16. }
  17. const fileData = await promises.readFile(FILE_PATH);
  18. return res.json({
  19. ok: true,
  20. text: fileData.toString("utf-8"),
  21. });
  22. };
  23. type PostResult = Promise<ExpressResponse<Option<unknown, { error: string }>>>;
  24. export const post = async (req: ExpressRequest, res: ExpressResponse): PostResult => {
  25. const isText = (body: unknown):
  26. body is MDText => (body as Record<string, unknown>).text !== undefined;
  27. if (!isText(req.body)) {
  28. return res.json({
  29. ok: false,
  30. error: "No text",
  31. });
  32. }
  33. if (!req.session?.userId) {
  34. return res.json({
  35. ok: false,
  36. error: "Not logged in, please log in",
  37. });
  38. }
  39. const { authorised } = await rpcClient.userAuthorised({ userId: req.session.userId });
  40. if (!authorised) {
  41. return res.json({
  42. ok: false,
  43. error: "Not authorised, please log in",
  44. });
  45. }
  46. await promises.writeFile(FILE_PATH, req.body.text);
  47. return res.json({ ok: true });
  48. };