Newer
Older
taehui / taehui-www / src / routers / essay.ts
@Taehui Taehui on 13 Mar 1 KB v1.0.0
import Router from "koa-router";
import { validateTotem } from "src/mws/avatar";
import { validateMillis } from "src/mws/millis";
import {
  doModifyEssay,
  getEssay,
  getLatestEssays,
  postEssay,
  wipeEssay,
} from "src/systems/essay";

const router = new Router();

router.get("/latest", async (ctx) => {
  const {
    query: { language },
  } = ctx;

  ctx.body = await getLatestEssays(language as string);
  ctx.status = 200;
});

router.get("/:essayID", async (ctx) => {
  const {
    request: { ip },
    params: { essayID },
    query: { language },
  } = ctx;

  const essay = await getEssay(Number(essayID), language as string, ip);
  if (essay) {
    ctx.body = essay;
    ctx.status = 200;
  } else {
    ctx.status = 404;
  }
});

router.put("/:essayID", validateMillis, validateTotem, async (ctx) => {
  const {
    params: { essayID },
    headers: { avatarID, level },
    request: {
      body: { title, text },
    },
  } = ctx;

  if (
    await doModifyEssay(
      Number(essayID),
      avatarID as string,
      title,
      text,
      Number(level),
    )
  ) {
    ctx.status = 204;
  } else {
    ctx.status = 403;
  }
});

router.delete("/:essayID", validateMillis, validateTotem, async (ctx) => {
  const {
    params: { essayID },
    headers: { avatarID, level },
  } = ctx;

  if (await wipeEssay(Number(essayID), avatarID as string, Number(level))) {
    ctx.status = 204;
  } else {
    ctx.status = 403;
  }
});

router.post("/:forumID", validateMillis, validateTotem, async (ctx) => {
  const {
    params: { forumID },
    headers: { avatarID, level },
    request: {
      body: { title, text },
    },
  } = ctx;

  const essayID = Number(
    await postEssay(forumID, avatarID as string, Number(level), title, text),
  );

  if (essayID !== -1) {
    ctx.body = { essayID };
    ctx.status = 201;
  } else {
    ctx.status = 403;
  }
});

export default router;