-
Notifications
You must be signed in to change notification settings - Fork 156
/
server.js
238 lines (164 loc) · 5.48 KB
/
server.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
app = express(),
expressValidator = require('express-validator');
/*Set EJS template Engine*/
app.set('views','./views');
app.set('view engine','ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true })); //support x-www-form-urlencoded
app.use(bodyParser.json());
app.use(expressValidator());
/*MySql connection*/
var connection = require('express-myconnection'),
mysql = require('mysql');
app.use(
connection(mysql,{
host : 'localhost',
user : 'root',
password : '',
database : 'test',
debug : false //set true if you wanna see debug logger
},'request')
);
app.get('/',function(req,res){
res.send('Welcome');
});
//RESTful route
var router = express.Router();
/*------------------------------------------------------
* This is router middleware,invoked everytime
* we hit url /api and anything after /api
* like /api/user , /api/user/7
* we can use this for doing validation,authetication
* for every route started with /api
--------------------------------------------------------*/
router.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
var curut = router.route('/user');
//show the CRUD interface | GET
curut.get(function(req,res,next){
req.getConnection(function(err,conn){
if (err) return next("Cannot Connect");
var query = conn.query('SELECT * FROM t_user',function(err,rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
res.render('user',{title:"RESTful Crud Example",data:rows});
});
});
});
//post data to DB | POST
curut.post(function(req,res,next){
//validation
req.assert('name','Name is required').notEmpty();
req.assert('email','A valid email is required').isEmail();
req.assert('password','Enter a password 6 - 20').len(6,20);
var errors = req.validationErrors();
if(errors){
res.status(422).json(errors);
return;
}
//get data
var data = {
name:req.body.name,
email:req.body.email,
password:req.body.password
};
//inserting into mysql
req.getConnection(function (err, conn){
if (err) return next("Cannot Connect");
var query = conn.query("INSERT INTO t_user set ? ",data, function(err, rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
res.sendStatus(200);
});
});
});
//now for Single route (GET,DELETE,PUT)
var curut2 = router.route('/user/:user_id');
/*------------------------------------------------------
route.all is extremely useful. you can use it to do
stuffs for specific routes. for example you need to do
a validation everytime route /api/user/:user_id it hit.
remove curut2.all() if you dont want it
------------------------------------------------------*/
curut2.all(function(req,res,next){
console.log("You need to smth about curut2 Route ? Do it here");
console.log(req.params);
next();
});
//get data to update
curut2.get(function(req,res,next){
var user_id = req.params.user_id;
req.getConnection(function(err,conn){
if (err) return next("Cannot Connect");
var query = conn.query("SELECT * FROM t_user WHERE user_id = ? ",[user_id],function(err,rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
//if user not found
if(rows.length < 1)
return res.send("User Not found");
res.render('edit',{title:"Edit user",data:rows});
});
});
});
//update data
curut2.put(function(req,res,next){
var user_id = req.params.user_id;
//validation
req.assert('name','Name is required').notEmpty();
req.assert('email','A valid email is required').isEmail();
req.assert('password','Enter a password 6 - 20').len(6,20);
var errors = req.validationErrors();
if(errors){
res.status(422).json(errors);
return;
}
//get data
var data = {
name:req.body.name,
email:req.body.email,
password:req.body.password
};
//inserting into mysql
req.getConnection(function (err, conn){
if (err) return next("Cannot Connect");
var query = conn.query("UPDATE t_user set ? WHERE user_id = ? ",[data,user_id], function(err, rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
res.sendStatus(200);
});
});
});
//delete data
curut2.delete(function(req,res,next){
var user_id = req.params.user_id;
req.getConnection(function (err, conn) {
if (err) return next("Cannot Connect");
var query = conn.query("DELETE FROM t_user WHERE user_id = ? ",[user_id], function(err, rows){
if(err){
console.log(err);
return next("Mysql error, check your query");
}
res.sendStatus(200);
});
//console.log(query.sql);
});
});
//now we need to apply our router here
app.use('/api', router);
//start Server
var server = app.listen(3000,function(){
console.log("Listening to port %s",server.address().port);
});