mysql查询和node响应结果的封装

  • Post author:
  • Post category:mysql


node响应结果的封装

node 响应结果封装(1)

class BaseModel{
    constructor(data,message){
        if(typeof data === 'string'){
            this.message = data
            data=null
            message=null
        }
        if(data){
            this.data = data
        }
        if(message){
            this.message = message
        }

    }

}

class SuccessModel extends BaseModel{
    constructor(data,message){
        super(data,message)
        this.errno=0
    }
}
class ErrorModel extends BaseModel{
    constructor(data,message){
        super(data,message)
        this.errno=-1
    }
}
module.exports={
    SuccessModel,
    ErrorModel
}

调用



return new SuccessModel(“登录成功”)


const { login } =require('../controller/user')
const { SuccessModel,ErrorModel}=require('../model/resModel')

const { set } =require('../db/redis')
// 获取cookie的过期时间
const getCookieExpires=()=>{
    const d=new Date()
    d.setTime(d.getTime()+(24*60*60*1000))
    console.log("d.toGMTString():",d.toGMTString())
    return d.toGMTString()
}

const handleUserRouter = (req,res)=>{
    const method=req.method

    const url=req.url
    const path = url.split('?')[0]
    console.log("path:",path)
    // 登录
    if(method === 'POST' && path ==='/api/user/login'){

        const { username,password}=req.body

        const result = login(username,password)
        return result.then(data=>{
            console.log("dataoo:",data)
            if(data.username){
                // 设置session
                console.log("req.session-user.js1:",req.session)
                req.session.username = data.username
                req.session.realname=data.realname

                // 同步到redis中
                set(req.sessionId,req.session)

                console.log("req.session-user.js2:",req.session)
                return new SuccessModel("登录成功")
            }
            return new ErrorModel('登录失败')
    
        })
       
    }
}
module.exports = handleUserRouter

node 响应结果封装(2)

创建

/models/Result.js

文件:

const {
  CODE_ERROR,
  CODE_SUCCESS
} = require('../utils/constant')

class Result {
  constructor(data, msg = '操作成功', options) {
    this.data = null
    if (arguments.length === 0) {
      this.msg = '操作成功'
    } else if (arguments.length === 1) {
      this.msg = data
    } else {
      this.data = data
      this.msg = msg
      if (options) {
        this.options = options
      }
    }
  }

  createResult() {
    if (!this.code) {
      this.code = CODE_SUCCESS
    }
    let base = {
      code: this.code,
      msg: this.msg
    }
    if (this.data) {
      base.data = this.data
    }
    if (this.options) {
      base = { ...base, ...this.options }
    }
    console.log(base)
    return base
  }

  json(res) {
    res.json(this.createResult())
  }

  success(res) {
    this.code = CODE_SUCCESS
    this.json(res)
  }

  fail(res) {
    this.code = CODE_ERROR
    this.json(res)
  }
}

module.exports = Result


constant.js

module.exports = {
    CODE_ERROR: -1,
    CODE_SUCCESS:0,
    debug:true,
    PWD_SALT:'admin_imooc_node'  //秘钥
  }

mysql查询与配置


config.js

module.exports = {

    host: 'localhost',

    user: 'root',

    password: '12990240pan',

    database: 'book'

  }


index.js【连接数据库法1】



escape:mysql.escape【一定要加】


const mysql = require('mysql')
const MYSQL_CONF=require('./config')
const {debug} = require('../utils/constant')
// 创建连接对象
con=mysql.createConnection(MYSQL_CONF)
// 开始连接
con.connect()

function querySql(sql){
    debug && console.log(sql)
    const promise = new Promise((resolve,reject)=>{
        try{
            con.query(sql,(err,results)=>{
                if(err){
                    debug && console.log('查询失败,原因:' + JSON.stringify(err))
                    reject(err)
                }else{
                    debug && console.log('查询成功', JSON.stringify(results))
                    resolve(results)
                }
            })  
        }
        catch(e){
            reject(e)
        }finally{
            con.end()
        }
    })
    return promise
}
module.exports={
    querySql,
    escape:mysql.escape
}


【连接数据库法2】

const mysql = require('mysql')
const {MYSQL_CONF }=require('../config/db')

// 创建连接对象
con=mysql.createConnection(MYSQL_CONF)

// 开始连接
con.connect()

// 统一执行sql的函数
function exec(sql){
    const promise = new Promise((resolve,reject)=>{
        // 查询
        con.query(sql,(err,result)=>{
            if(err){
            reject(err)
            // console.error(err)
            return
            }
            resolve(result)
            // console.log("result:",result)
        })
    })
return promise
}

module.exports={
    exec,
    escape:mysql.escape
}



版权声明:本文为pansuyong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。