-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
243 lines (214 loc) · 6.56 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
239
240
241
242
243
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const User = require('./server/models/user');
const Recipe = require('./server/models/recipe');
const auth = require('./server/middleware/auth');
const bcrypt = require('bcryptjs');
// const app = require('./server/app');
const log4js = require('log4js');
log4js.configure({
appenders: { book: { type: 'file', filename: 'logs/classifier_be.log' }, out: { type: 'stdout' } },
categories: { default: { appenders: ['book', 'out'], level: 'debug' } }
});
const logger = log4js.getLogger('book');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"PUT,DELETE, POST, GET, OPTIONS"
)
next();
});
// app.options('/users/storeRecipes', cors())
app.post('/users/signUp', async (req, res,next) => {
const user = new User(req.body)
try {
user.password = await bcrypt.hash(user.password, 8);
await user.save();
const token = await user.generateAuthToken();
res.status(201).json({
message: "user created",
user: user,
token: token });
} catch (err) {
if (11000 === err.code) {
var MongooseError = require('mongoose/lib/error')
var valError = new MongooseError.ValidationError(err)
// valError.errors["xxx"] = new MongooseError.ValidatorError('xxx', 'Email already registered. Plse login',err.err)
valError.message = "Email already registered. Please login"
err = valError
}
logger.error('Error in registering', err.message);
res.status(500).json({
"message": err.message
});
}
});
app.post('/users/login', async (req, res,next) => {
try {
const user = await User.findByCredentials(req.body.email, req.body.password);
const AuthTokenUserData = await user.generateAuthToken();
res.status(200).json({
token: AuthTokenUserData.token,
userId: AuthTokenUserData.userId
});
} catch (e) {
logger.error('Error', e);
res.status(500).json(
{"message": e.message}
)
}
})
app.post('/users/logout', auth, async (req, res,next) => {
try {
req.user.tokens = [];
await req.user.save();
res.status(200).send();
} catch (e) {
res.send(e);
}
})
app.post('/recipes', auth, async(req, res, next) => {
const recipe = new Recipe({
name: req.body.name,
description: req.body.description,
imagePath: req.body.imagePath,
ingredients: req.body.ingredients,
creator: req.userData._id
});
recipe.save().then(createdRecipe => {
res.status(200).json({
message: "recipe fetched successfully",
recipeId: createdRecipe._id
})
})
})
app.get('/recipes', async(req, res,next) => {
await Recipe.find((err, recipes) => {
if(err) {
logger.error("Error in retriving recipes", err.message)
res.status(201).json({
"error": err.message
})
}
else{
res.status(200).json({
"message": "Recipes get successfully",
"recipes": recipes
})
}
});
})
app.get('/recipes/:id', async(req, res, next) => {
try{
const recipe = await Recipe.findById(req.params.id);
if(!recipe) {
throw new Error();
}
res.status(200).json(recipe)
}catch(e) {
res.status(201).json({
message: "Recipe not found"
})
}
})
app.delete('/recipes/:id', auth, async(req, res, next) => {
await Recipe.deleteOne({_id: req.params.id, creator: req.userData._id}, (err, result) => {
if(err) {
res.status(201).json({
"message": err.message
})
console.log(err)
}
else{
if(result.n > 0) {
console.log("deleted recipe", result)
res.status(200).json({
"message": "Recipe was deleted"
})
}
else{
res.status(401).json({
"message": "Not authorized"
})
}
}
})
})
app.put('/recipes/:id', auth, (req, res, next) => {
console.log(req.body)
const recipe = new Recipe({
_id: req.body.id,
name: req.body.name,
description: req.body.description,
imagePath: req.body.imagePath,
ingredients: req.body.ingredients,
})
Recipe.updateOne({_id: req.body.id, creator: req.userData._id}, recipe, (err, result) => {
if(err) {
logger.error('Error in updating recipe')
}
else {
if(result.nModified > 0) {
res.status(200).json({
"message": "Recipe is updated",
"updatedRecipe": result
})
}
else{
res.status(401).json({
"message": "Authorization denied" })
}
}
})
})
// module.exports = app;
const normalizePort = val => {
let port = parseInt(val,10);
if(isNaN(port)) {
return val;
}
if(port >= 0) {
return port;
}
return false;
}
const onError = error => {
if(error.syscall !== 'listen') {
throw error;
}
const bind = typeof addr === "string" ? "pipe " + addr : "port " + port;
switch(error.code) {
case "EACCES":
logger.error(bind + " requires elevated priviledges");
process.exit(1);
break;
case "EADDRINUSE":
logger.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}
const onListening = ()=> {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + port;
logger.debug("Listening on " + bind);
}
const port = normalizePort(process.env.PORT || 3000);
app.set('port', port);
let distDir = __dirname + "/dist/";
app.use(express.static(distDir));
const server = http.createServer(app);
server.on("error", onError);
server.on("listening", onListening);
server.listen(port);