-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
51 lines (42 loc) · 1.17 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
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var database = require('./databaseRequests.js');
var app = express();
app.use(express.static('public'));
app.use(bodyParser.json());
app.listen(3000, function () {
console.log('Listening on port 3000...');
});
app.get('/meals', function (req, res) {
database.getMeals(function (allMeals) {
res.status(200).json(allMeals);
});
});
app.get('/meals/:id', function (req, res) {
findMeal(req, res, function (meal) { res.json(meal); });
});
app.post('/meals', function (req, res) {
var attributes = req.body;
database.addMeal(attributes, function (newItemArray) {
res.status(200).json(newItemArray[0]);
});
});
app.delete('/meals/:id', function (req, res) {
findMeal(req, res, function (meal) {
database.removeMeal(meal.meal_id, function (sqlres) {
res.status(200).json(meal);
});
});
});
function findMeal(req, res, callback) {
var id = parseInt(req.params.id);
database.getMealById(id, function (mealsArray) {
var meal = mealsArray[0];
if (meal) {
callback(meal);
} else {
res.status(401).json( {status: 'not exists'} );
}
});
}