node最佳实践7-统一返回结构体

264 阅读1分钟

设计一个对象,用此来固定返回结构。

新增src/libs/result.js

class BaseResult {
  constructor(code,msg){
    this.code = code
    this.msg = msg
  }
  static SUCCESS = new BaseResult(200,'成功')
  static FAILED = new BaseResult(500,'失败')
  static RECORD_NOT_FOUND = new BaseResult(500,'查无对应数据')
  static VALIDATE_FAILED = new BaseResult(400,'参数校验失败')
  static API_NOT_FOUND = new BaseResult(404,'接口不存在')
  static API_BUSY = new BaseResult(700,'操作过于频繁') 
}
export class Result {
  constructor(code, msg, data){
    this.code = code
    this.msg = msg
    this.data = data
  }
  static success(data){
    return new Result(BaseResult.SUCCESS.code,BaseResult.SUCCESS.msg,data)
  } 
  static failed(errData){
    return new Result(BaseResult.FAILED.code,BaseResult.FAILED.msg,errData)
  }
  static validateFailed(params){
    return new Result(BaseResult.VALIDATE_FAILED.code,BaseResult.VALIDATE_FAILED.msg,params)
  }
  static recordNotFound(data){
    return new Result(BaseResult.RECORD_NOT_FOUND.code,BaseResult.RECORD_NOT_FOUND.msg,data)
  }
}

优化book.controller.js

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

export const getRecordsByPage = (req,res) => {
  const { page,pageSize } = req.query
  Book.findAll({
    attributes: ['id','name','author'],
    limit: pageSize,
    offset: (page-1) * pageSize,
    order: [['id','DESC']]
  }).then(books => {
    return res.json(Result.success(books))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}
export const getRecordById = (req,res) => {
  const id = req.params.id
  Book.findByPk(id).then(book => {
    return res.json(Result.success(book))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}
export const deleteRecordById = (req,res) => {
  const {id} = req.body
  Book.destroy({
    where: {id: id}
  }).then((book) => {
    return res.json(Result.success(null))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}
export const addRecord = (req,res) => {
  let { name, author } = req.body
  Book.create({
    name, author
  }).then(book => {
    return res.json(Result.success(book))
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}
export const updateRecord = (req,res) => {
  let {id,name,author} = req.body
  Book.findOne({
    where:{id: id}
  }).then(book => {
    if(book){
      book.update({
        name,author
      }).then(newBook =>{
        return res.json(Result.success(newBook))
      })
    }else{
      return res.json(Result.recordNotFound({id}))
    }
  }).catch(err => {
    return res.status(500).json(Result.failed(err))
  })
}