灏天阁

Node/Koa2[71]:分析@关系并存储

· Yin灏

创建微博的时候,收集@信息

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

const { getUserInfo } = require("../services/user");
const { createAtRelation } = require("./services/at-relation");

const xss = require("xss");

async function create({ userId, content, image }) {
  // 调用 services 层
  // 分析并收集 content 中的 @ 用户
  const atUserNameList = [];
  content = content.replace(
    /@(.+?)\s-\s(\w+?)\b/g,
    (matchStr, nickName, userName) => {
      atUserNameList.push(userName);
      return matchStr;
    }
  );
  // 根据 @ 用户名查询用户信息
  const atUserList = await Promise.all(
    atUserNameList.map(userName => getUserInfo(userName));
  )
  // 根据用户信息获取用户 id
  const atUserIdList = atUserList.map(user => user.id);

  try {
    const blog = await createBlog({ userId, content: xss(content), image });

    // 创建 @ 关系
    // 调用 services
    await Promise.all(atUserIdList.map(userId => createAtRelation(blog.id, userId)));

    return new SuccessModel(blog);
  } catch (ex) {
    console.error(ex.message, ex.stack);
    return new ErrorModel(createBlogFailInfo);
  }
}

module.exports = {
  create,
};

新建 services 层

// src/services/at-relation.js
const { AtRelation } = require("../db/model/index");
async function createAtRelation(blogId, userId) {
  const result = await AtRelation.create({
    blogId,
    userId,
  });
}
module.exports = {
  createAtRelation,
};

- Book Lists -