灏天阁

Node/Koa2[54]: 微博广场

· Yin灏
  • 页面和模板(后端渲染,用到了缓存)

  • 加载更多

  • 单元测试

页面和模板

  • 页面模板

src/views/square.ejs

  • 页面路由

src/routes/view/blog.js

//...
const { getSquareBlogList } = require("../../controller/blog-square");
// 广场
router.get("/square", loginRedirect, async (ctx, next) => {
  // controller 层
  const result = await getSquareBlogList(0);
  const { isEmpty, blogList, pageSize, pageIndex, count } = result;
  await ctx.render("square", {
    blogData: {
      isEmpty,
      blogList,
      pageSize,
      pageIndex,
      count,
    },
  });
});
//...

controller 层

src/controller/blog-square.js

const { getSquareCacheList } = require(../cache/blog);
//...
async function getSquareBlogList(pageIndex = 0) {
  // cache 层
  const result = await getSquareCacheList(pageIndex, PAGE_SIZE);
  const blogList = result.blogList;
  return new SuccessModel({
    isEmpty: blogList.length === 0,
    blogList,
    pageSize: PAGE_SIZE,
    pageIndex,
    count: result.count
  })
}
//...

blog 相关的缓存处理

src/cache/blog.js

// 微博广场缓存层
const { get, set } = require("./_redis");
const { getBlogListByUser } = require("../services/blog");

const KEY_PREFIX = "weibo:square:";

async function getSquareCacheList(pageIndex, pageSize) {
  const key = `${KEY_PREFIX}${pageIndex}_${pageSize}`;
  // 尝试获取缓存
  const cacheResult = await get(key);
  if (cacheResult !== null) {
    // 获取缓存功能
    return cacheResult;
  }
  // 没有缓存,则读取数据库
  const result = await getBlogListByUser({
    pageIndex,
    pageSize,
  });
  // 设置缓存,过期时间 1min
  set(key, result, 60);
  return result;
}

module.exports = {
  getSquareCacheList,
};

加载更多

src/routes/api/blog-square.js

const router = require("koa-router")();
const { loginCheck } = require("../../middlewares/loginChecks");
const { getSquareBlogList } = require("../../controller/blog-square");
const { getBlogListStr } = require("../../utils/blog");
router.prefix("/api/square");
// 加载更多
router.get("/loadMore/:pageIndex", loginCheck, async () => {
  const { pageIndex } = ctx.params;
  pageIndex = parseInt(pageIndex);
  const result = await getSquareBlogList(pageIndex);
  // 渲染模板字符串
  result.data.blogListTpl = getBlogListStr(result.data.blogList);
  ctx.body = result;
});
//...
module.exports = router;

app.js 中注册

//...
const squareAPIRouter = require("./routes/api/blog-square");
//...
app.use(squareAPIRouter.routes(), squareAPIRouter.allowedMethods());
//...

- Book Lists -