forked from artilery/blog-api
-
Notifications
You must be signed in to change notification settings - Fork 4
/
app.js
101 lines (83 loc) · 2.14 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// When the app starts
var express=require('express');
var app = express();
var bodyParser = require('body-parser');
var Promise = require('bluebird');
var dbConfig={
client:'mysql',
connection:{
host:'localhost',
user:'root',
password:'your_password',
database:'blog',
charset:'utf8'
}
};
var knex = require('knex')(dbConfig);
var bookshelf = require('bookshelf')(knex);
app.set('bookshelf', bookshelf);
var allowCrossDomain=function(req,res,next){
res.header('Access-Control-Allow-Origin','*');
next();
};
app.use(allowCrossDomain);
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())
// parse application/json
app.use(bodyParser.json())
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
// elsewhere, to use the bookshelf client:
var bookshelf = app.get('bookshelf');
//model setup
// relationships and login methods
var Article=bookshelf.Model.extend({
tableName:'article'
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
//routes
app.get('/',function(req,res){
res.send("blog-api up and running");
});
/* GET /api/article */
app.get('/api/article',function(req,res){
new Article().fetchAll()
.then(function(articles){
res.send(articles.toJSON());
}).catch(function(error){
console.log(error);
res.send('An error occured');
});
});
/* GET /api/article/:article_id */
app.get('/api/article/:article_id',function(req,res){
var article_id=req.params.article_id;
new Article().where('id',article_id)
.fetch()
.then(function(article){
res.send(article.toJSON());
}).catch(function(error){
console.log(error);
res.send('Error retrieving article');
});
});
/* POST /api/article */
app.post('/api/article',function(req,res){
var article=new Article({
title:req.body.title,
body:req.body.body,
author:req.body.author
});
article.save().then(function(saved_article){
res.send(saved_article.toJSON());
}).catch(function(error){
console.log(error);
res.send('Error saving article')
});
});
app.listen(3000,function(){
console.log("Express started at port 3000");
});