md.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. export interface MDText {
  8. text: string;
  9. }
  10. const FILE_PATH = join(ENVIRONMENT.dataPath, "rules.md");
  11. type GetResult = Promise<ExpressResponse<Option<MDText, { error: string }>>>;
  12. export const get = async (req: ExpressRequest, res: ExpressResponse): GetResult => {
  13. if (!existsSync(FILE_PATH)) {
  14. return res.json({
  15. ok: true,
  16. text: "",
  17. });
  18. }
  19. const fileData = await promises.readFile(FILE_PATH);
  20. return res.json({
  21. ok: true,
  22. text: fileData.toString("utf-8"),
  23. });
  24. };
  25. type PostResult = Promise<ExpressResponse<Option<unknown, { error: string }>>>;
  26. export const post = async (req: ExpressRequest, res: ExpressResponse): PostResult => {
  27. const isText = (body: unknown):
  28. body is MDText => body instanceof Object
  29. && (body as Record<string, unknown>).text !== undefined;
  30. if (!isText(req.body)) {
  31. return res.json({
  32. ok: false,
  33. error: "No text",
  34. });
  35. }
  36. if (!req.session?.userId) {
  37. return res.json({
  38. ok: false,
  39. error: "Not logged in, please log in",
  40. });
  41. }
  42. const { authorised } = await rpcClient.userAuthorised({ userId: req.session.userId });
  43. if (!authorised) {
  44. return res.json({
  45. ok: false,
  46. error: "Not authorised, please log in",
  47. });
  48. }
  49. await promises.writeFile(FILE_PATH, req.body.text);
  50. return res.json({ ok: true });
  51. };