版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/funkstill/article/details/85715768
添加数据库
往 Node 程序中添加数据库而言,并没有一定之规,但一般会涉及下面几个步骤。
- 决定想要用的数据库系统。
- 在 npm 上看看那些实现了数据库驱动或对象关系映射(ORM)的热门模块。
- 用 npm --save 将模块添加到项目中。
- 创建模型,封装数据库访问 API。
- 把这些模型添加到 Express 路由中。
制作自己的模型 API
文章应该能被创建、被获取、被删除,所以模型类 Article 应该提供下面这些方法:
- Article.all(cb)——返回所有文章;
- Article.find(id, cb) ——给定 ID,找到对应的文章;
- Article.create({ title,content }, cb)——创建一篇有标题和内容的文章;
- Article.delete(id, cb) —— 根据 ID 删除文章。
npm install --save sqlite3
模型类 Article
//db.js
const sqlite3 = require('sqlite3').verbose();
const dbName = 'later.sqlite';
const db = new sqlite3.Database(dbName);
db.serialize(()=>{
const sql = `
CREATE TABLE IF NOT EXISTS articles
(id integer primary key,title,content TEXT)
`;
db.run(sql);
});
class Article {
static all(cb){
db.all('SELECT * FROM articles',cb);
}
static find(id,cb){
db.get('SELECT * FROM articles WHERE id = ?',id,cb);
}
static create(data,cb){
const sql = 'INSERT INTO articles(title,content) VALUES (?,?)';
db.run(sql,data.title,data.content,cb);
}
static delete(id,cb){
if(!id) return cb(new Error('Please provide an id'));
db.run('DELETE FROM articles WHERE id = ?',id,cb);
}
}
module.exports = db;
module.exports.Article = Article;
将 Article 模块添加到 HTTP 路由中
const express = require('express');
const app = express();
//const articles = [{title:'Example'}];
const bodyParser = require('body-parser');
const Article = require('./db').Article;//加载数据库模块
app.set('port',process.env.PORT||3000);
app.use(bodyParser.json());//支持编码为JSON的请求体
app.use(bodyParser.urlencoded({extended:true}));//支持编码为表的请求体
app.get('/articles',(req,res,next)=>{//获取所有文章
Article.all((err,articles)=>{
if(err) return next(err);
res.send(articles);
});
});
app.post('/articles',(req,res,next)=>{//创建一篇文章
const article = {title:req.body.title};
articles.push(article);
res.send(article);
});
app.get('/articles/:id',(req,res,next)=>{//获取指定文章
const id = req.params.id;
Article.find(id,(err,article)=>{
if(err) return next(err);
res.send(articel);
});
});
app.delete('/articles/:id',(req,res,next)=>{//删除指定文章
const id = req.params.id;
Article.delete(id,(err)=>{
if(err) return next(err);
res.send({message:'Deleted'});
});
});
app.listen(app.get('port'),()=>{
console.log('App started on port',app.get('port'));
});
module.exports = app;
让文章可读并把它存起来
RESTful API 已经搭建好了,数据也可以持久化到数据库中了,接下来该写代码把网页转换成简化版的“阅读视图”了。
npm install node-readability --save
const read = require('node-readability');
app.post('/articles',(req,res,next)=>{//创建一篇文章
const url = req.body.url;//从POST消息体中得到的URL
read(url,(err,result)=>{
//用readability模块获取URL指向页面
if(err||!result) res.status(500).send('Error downloading article');
Article.create(
{title:result.title,content:result.content},
(err,article)=>{
if(err) return next(err);
res.send('OK');
}
)
})
});