All files / modules/drafts drafts.controller.ts

0% Statements 0/55
0% Branches 0/1
0% Functions 0/1
0% Lines 0/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78                                                                                                                                                           
import Router from '@koa/router';
import { Context } from 'koa';
import { optionalAuth } from '../../middleware/auth';
import { prisma } from '../../models';
 
const TEST_USER_ID = '1';
const router = new Router();
 
// 获取草稿列表
router.get('/', optionalAuth, async (ctx: Context) => {
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const { type } = ctx.query as { type?: string };
  const where: any = { userId: parseInt(userId) };
  if (type) where.type = type;
  const drafts = await prisma.draft.findMany({
    where,
    orderBy: { updatedAt: 'desc' },
  });
  ctx.body = { code: 0, message: 'success', data: drafts };
});
 
// 获取单个草稿
router.get('/:id', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  const draft = await prisma.draft.findUnique({
    where: { id: parseInt(id) },
  });
  ctx.body = { code: 0, message: 'success', data: draft };
});
 
// 保存草稿
router.post('/', optionalAuth, async (ctx: Context) => {
  const userId = ctx.state.user?.userId || TEST_USER_ID;
  const data = ctx.request.body as {
    type: string;
    title?: string;
    content?: string;
    metadata?: string;
  };
  const draft = await prisma.draft.create({
    data: {
      userId: parseInt(userId),
      type: data.type,
      title: data.title,
      content: data.content,
      metadata: data.metadata,
      autoSavedAt: new Date(),
    },
  });
  ctx.body = { code: 0, message: 'success', data: draft };
});
 
// 更新草稿
router.put('/:id', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  const data = ctx.request.body as {
    title?: string;
    content?: string;
    metadata?: string;
  };
  const draft = await prisma.draft.update({
    where: { id: parseInt(id) },
    data: { ...data, autoSavedAt: new Date() },
  });
  ctx.body = { code: 0, message: 'success', data: draft };
});
 
// 删除草稿
router.delete('/:id', optionalAuth, async (ctx: Context) => {
  const { id } = ctx.params;
  await prisma.draft.delete({
    where: { id: parseInt(id) },
  });
  ctx.body = { code: 0, message: 'success' };
});
 
export default router;