md.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 as Record<string, unknown>).text !== undefined;
  29. if (!isText(req.body)) {
  30. return res.json({
  31. ok: false,
  32. error: "No text",
  33. });
  34. }
  35. if (!req.session?.userId) {
  36. return res.json({
  37. ok: false,
  38. error: "Not logged in, please log in",
  39. });
  40. }
  41. const { authorised } = await rpcClient.userAuthorised({ userId: req.session.userId });
  42. if (!authorised) {
  43. return res.json({
  44. ok: false,
  45. error: "Not authorised, please log in",
  46. });
  47. }
  48. await promises.writeFile(FILE_PATH, req.body.text);
  49. return res.json({ ok: true });
  50. };