1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import { Request as ExpressRequest, Response as ExpressResponse } from "express";
- import { existsSync, promises } from "fs";
- import { join } from "path";
- import { ENVIRONMENT } from "src/utils/environment";
- import { Option } from "@shared/common/async_utils";
- import { rpcClient } from "src/utils/rpc";
- export interface MDText {
- text: string;
- }
- const FILE_PATH = join(ENVIRONMENT.dataPath, "rules.md");
- type GetResult = Promise<ExpressResponse<Option<MDText, { error: string }>>>;
- export const get = async (req: ExpressRequest, res: ExpressResponse): GetResult => {
- if (!existsSync(FILE_PATH)) {
- return res.json({
- ok: true,
- text: "",
- });
- }
- const fileData = await promises.readFile(FILE_PATH);
- return res.json({
- ok: true,
- text: fileData.toString("utf-8"),
- });
- };
- type PostResult = Promise<ExpressResponse<Option<unknown, { error: string }>>>;
- export const post = async (req: ExpressRequest, res: ExpressResponse): PostResult => {
- const isText = (body: unknown):
- body is MDText => (body as Record<string, unknown>).text !== undefined;
- if (!isText(req.body)) {
- return res.json({
- ok: false,
- error: "No text",
- });
- }
- if (!req.session?.userId) {
- return res.json({
- ok: false,
- error: "Not logged in, please log in",
- });
- }
- const { authorised } = await rpcClient.userAuthorised({ userId: req.session.userId });
- if (!authorised) {
- return res.json({
- ok: false,
- error: "Not authorised, please log in",
- });
- }
- await promises.writeFile(FILE_PATH, req.body.text);
- return res.json({ ok: true });
- };
|