灏天阁

Node/Koa2[74]:标记为已读

· Yin灏

标记为已读

// src/routes/view/blog.js
const { getAtMeBlogList, markAsRead } = require("../../controller/blog-at");
router.get("/at-me", loginRedirect, async () => {
  const { id: userId } = ctx.session.userInfo;
  const atCountResult = await getAtMeCount(userId);
  const { count: atCount } = atCountResult.data;
  // 获取第一页列表
  // 调用 controller
  const result = await getAtMeBlogList(userId);
  const { isEmpty, blogList, pageSize, pageIndex, count } = result.data;
  // 渲染页面
  await ctx.render("atMe", {
    atCount,
    blogData: {
      isEmpty,
      blogList,
      pageSize,
      pageIndex,
      count,
    },
  });
  // 标记为已读
  if (atCount > 0) {
    // 调用 controller
    await markAsRead(userId);
  }
});

controller

// src/controller/blog-at.js
const { updateAtRelation } = require("../services/at-relation");
async function markAsRead(userId) {
  // 调用 services
  try {
    await updateAtRelation({ newIsRead: true }, { userId, isRead: false });
  } catch (ex) {
    console.error(ex);
  }
}
module.exports = {
  //...
  markAsRead,
};

services

// src/services/at-relation.js
async function updateAtRelation({ newIsRead }, { userId, isRead }) {
  // 更新数据
  const updateData = {};
  if (newIsRead) {
    updateData.isRead = newIsRead;
  }
  // 查询条件
  const whereData = {};
  if (userId) {
    whereData.userId = userId;
  }
  if (isRead) {
    whereData.isRead = isRead;
  }
  // 执行更新
  const result = await AtRelation.update(updateData, {
    where: whereData,
  });
  return result[0] > 0;
}

- Book Lists -