node最佳实践5-sequelize关联关系2

80 阅读1分钟

数据和模型准备好之后开始创建congtroller和route

优化book.controller的getRecordById方法,新增authorName和categoryName的返回

export const getRecordById = (req,res) => {
  const id = req.params.id
  Book.findByPk(id).then(async(book) => {
    const author = await book.getAuthor()
    const category = await book.getCategory()
    console.log(book)
    const data = {
      ...book.dataValues,
      createdAt: getDateTime(book.dataValues.createdAt),
      updatedAt: getDateTime(book.dataValues.updatedAt),
      authorName:author?.name,
      categoryName:category?.name
    }
    return res.json(Result.success(data))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}

getAuthor和getCategory是关联关系建立后自动产生的方法。

Screenshot 2023-03-07 at 15.29.00.png libs/tools.js

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
export const getDate = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}
export const getDateTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const seconds = date.getSeconds()
  const dateStr = [year, month, day].map(formatNumber).join('-')
  const timeStr = [hours, minutes, seconds].map(formatNumber).join(':')
  return dateStr + ' ' + timeStr
}

Category

routes/category.route.js

import express from 'express'
const router = express.Router()
import {
  getRecords,
  getCategoryBooks,
  deleteRecord,
  createRecord
} from '../controllers/category.controller'

router.get('/',getRecords)
router.post('/getBooks',getCategoryBooks)
router.post('/delete',deleteRecord)
router.post('/create',createRecord)
export default router

controllers/category.controller.js

import { Category,Book } from '../models'
import { Result } from '../libs/result'

export const getRecords = (req,res) => {
  Category.findAll({
    attributes: ['id','name'],
  }).then(categories => {
    return res.json(Result.success(categories))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}
export const getCategoryBooks = (req,res) => {
  const { id } = req.body
  // Category.findByPk(id).then(async(category) => {
  //   if(category){
  //     const books = await category.getBooks()
  //     console.log('books',books);
  //     return res.json(Result.success(books))
  //   }else{
  //     return res.json(Result.recordNotFound({id}))
  //   }
  // }).catch(err => {
  //   return res.status(400).json(Result.failed(err))
  // })
  Category.findAll({
    attributes: ['id','name'],
    where:{id},
    include: {model: Book,attributes:['id','name']}
  }).then(books => {
    return res.json(Result.success(books))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}
export const deleteRecord = (req,res) => {
  const {id} = req.body
  Category.destroy({
    where: {id: id}
  }).then(() => {
    return res.json(Result.success(null))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}
export const createRecord = (req,res) => {
  let { name } = req.body
  console.log('name=',name);
  Category.create({
    name
  }).then(category => {
    return res.json(Result.success(category))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}

在获取某一类型的所有书籍这个方法(getCategoryBooks)上,有eager loading和lazy loading两种区分,参考Eager Loading

Screenshot 2023-03-07 at 15.30.19.png