前面讲到了博客的增删改查,是做了封装的,现在我们就讲一讲逻辑处理的大体操作。首先你需要什么参数,无论是哪一项操作,都需要确定目标,这个目标可以是实体,可以是实体的一个特征。
这里我们用到了sql的基本查询语句,还涉及到node连接数据库等。不比比,上代码。
首先连接数据库,
const mysql = require('mysql')
const { MYSQL_CONF } = require('../conf/db')
// 创建链接对象
const con = mysql.createConnection(MYSQL_CONF)
//开始连接
con.connect()
//统一执行sql函数
function exce(sql){
const promise = new Promise((resolve, reject) => {
con.query(sql, (err, result) => {
if (err) {
reject(err)
return
}
resolve(result)
})
})
return promise
}
module.exports = {
exce,
excape:mysql.escape
}
获得列表
const getList = (author, keyword) => {
let sql = `select * from blogs where 1=1 `
if (author) {
sql += `and author='${author}' `
}
if (keyword) {
sql += `and title like '%${keyword}%' `
}
sql += `order by createtime desc;`
// 返回 promise
return exec(sql)
//获取某一细节
const getDetail = (id)=>{
const sql = `select from blogs where id = '${id}'`
return exce.then(rows=>{
return rows[0]
}
)
}
//新建博客
const newBlog = (blogData = {}) => {
// blogData 是一个博客对象,包含 title content author 属性
const title = xss(blogData.title)
// console.log('title is', title)
const content = xss(blogData.content)
const author = blogData.author
const createTime = Date.now()
const sql = `insert into blogs (title, content, createtime, author)
values ('${title}', '${content}', ${createTime}, '${author}')`
return exec(sql).then(insertData=>{
id:insertData.insertId
})
//删除博客
const delBlog = (id, author) => {
// id 就是要删除博客的 id
const sql = `delete from blogs where id='${id}' and author='${author}';`
return exec(sql).then(delData => {
// console.log('delData is ', delData)
if (delData.affectedRows > 0) {
return true
}
return false
})
}
更新博客
const updateBlog = (id,blogData)=>{
const title = xss(blogData.title)
const content = xss(blogData.content)
const sql = `updata blogs set title = '${title}' and content = '${contnet}' where id = '${id}' `
return exec(sql).then({
updateData => {
// console.log('updateData is ', updateData)
if (updateData.affectedRows > 0) {
return true
}
return false
})
}
ok,这里讲的都是博客的操作,下面来讲讲用户登录的操作,其实大体上都差不多。