跟我一起学NodeJS之操作数据库
2020-04-13 本文已影响0人
喜剧之王爱创作

之前的笔记中讲到了如何在nodejs中链接数据库, 以及我们将链接数据库封装为一个方法,这节我们将介绍在项目中使用我们的封装去操作数据库。
处理Get请求
因为之前我们在controller中使用的是假数据,所以我们要连接数据库,就要先从controller中入手了,以获取博客列表为例,其他GET
请求同理。
//controller中blog.js
const { exec } = require('../db/mysql')
const getList = (author, keyword) => {
let sql = `select * from blogs where 1=1 `//这里1=1是一个占位作用,避免author或者keyword不存在时sql语句报错
if (author) {
sql += `and author='${author}' `
}
if (keyword) {
sql += `and title like '%${keyword}%' `
}
sql += `order by createtime desc;`
// 返回promise
return exec(sql)
}
这里有几点主要注意:
- 在拼sql时,‘where 1=1’是为了author或keyword为空时,sql依然是合法的。
- 我们要将
exec
返回的promise
返回,以供router中使用
controller过后,就会走到routrt中,我们按照这个流程对router进行改造
//router中的blog.js
//获取博客列表
if (method === 'GET' && req.path === '/api/blog/list') {
const author = req.query.author || ''
const keyword = req.query.keyword || ''
// const listData = getList(author,keyword)
// return new SuccessModel(listData)
const result = getList(author, keyword)
return result.then(listData => {
return new SuccessModel(listData)
})
}
上面代码中注意两点
- 传参不变,只是处理结果上的改变吗,因为comtroller中返回一个
promise
,所以,这里要从promise中获取 - 我们仍然要返回一个promise以供我们在app中使用。
最后我们对app.js
进行改造
const blogResult = handleBlogRouter(req, res)
if (blogResult) {
blogResult.then(blogData => {
res.end(
JSON.stringify(blogData)
)
})
return
}
同理,我们将之前的直接处理数据,变为处理一个promise。
处理POST请求
处理post
请求同理,我们不需要再在app.js和router中做改动,直接改动原先使用假数据的controller即可。
const newBlog = (blogData = {}) => {
//blogData是一个博客对象,包含title content, author 等属性
const title = blogData.title
const content = 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 => {
return {
id: insertData.insertId
}
})
}
操作和GET
请求无太大差异,只需要注意一下一点
- 因为
POST
请求返回一个操作后的对象,所以我们在返回结果的时候需要从数据库操作对象中提取必要的信息
到这里,在NodeJs中操作数据库已经将完,希望同学们可以举一反三把每一个接口都自己手打一遍,接下来,我们就是讲登陆了。