灏天阁

Node/Koa2[47]: 创建微博API

· Yin灏

开发接口

  • 回顾架构设计图

  • 开发接口(考虑 xss 攻击)

  • 数据格式校验

新建接口路由

src/routes/api/blog-home.js

const router = require("koa-router")();
const { loginCheck } = require("../../middlewares/loginChecks");
const { create } = require("../../controller/blog-home");

router.prefix("/api/blog");

router.post("/create", loginCheck, async (ctx, next) => {
  const { content, image } = ctx.request.body;
  const { id: userId } = ctx.session.userInfo;
  // controller 层
  ctx.body = await create({
    userId,
    content,
    image,
  });
});

module.exports = router;

app.js 中注册路由

// app.js
//...
const blogHomeAPIRouter = require("./routes/api/blog-home");
//...
app.use(blogHomeAPIRouter.routes(), blogHomeAPIRouter.allowedMethods());

controller 层

src/controller/blog-home.js

const { createBlog } = require("../services.blog");
const { SuccessModel, ErrorModel } = require("../model/ResModel");
const { createBlogFailInfo } = require("../model/ErrorInfo");

async function create({ userId, content, image }) {
  // services 层
  try {
    const blog = await createBlog({ userId, content, image });
    return new SuccessModel(blog);
  } catch (ex) {
    console.error(ex.message, ex.stack);
    return new ErrorModel(createBlogFailInfo);
  }
}

module.exports = {
  create,
};

services 层

src/services/blog.js

const { Blog } = require("../db/model/index");

async function createBlog({ userId, content, image }) {
  const result = await Blog.create({
    userId,
    content,
    image,
  });
  return result.dataValues;
}

module.exports = {
  createBlog,
};

- Book Lists -