Add server implementation

This commit is contained in:
Arti Zirk 2017-06-10 22:26:00 +03:00
parent 85e046f2dd
commit 611608869c

View File

@ -2,9 +2,12 @@
const express = require('express'); const express = require('express');
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express(); const app = express();
app.use(morgan('combined'));
app.set('etag', false);
app.use(bodyParser.json()); // before request handlers app.use(bodyParser.json()); // before request handlers
app.use(express.static('./')); app.use(express.static('./'));
@ -32,6 +35,7 @@ var contacts = [
"phone": "789" "phone": "789"
} }
] ]
var lastContactId = 3;
app.use(errorHandler); // after request handlers app.use(errorHandler); // after request handlers
@ -55,19 +59,45 @@ function getContact(req, resp) {
return; return;
} }
} }
resp.json(""); resp.status(404).end("Contact Not Found");
} }
function addContact(req, resp) { function addContact(req, resp) {
var task = request.body; var contact = req.body;
console.log(task);
contacts.push({
"_id": ++lastContactId,
"name": contact.name,
"phone": contact.phone
})
resp.status(201).end("Created");
} }
function changeContact(req, resp) { function changeContact(req, resp) {
var task = request.body; var id = req.params.id;
console.log(task); var changedContact = req.body;
for (let contact of contacts) {
if (contact._id == id) {
contact.name = changedContact.name;
contact.phone = changedContact.phone
resp.status(200).end("Changed");
return;
}
}
resp.status(404).end("Contact Not Found");
} }
function deleteContact(req, resp) { function deleteContact(req, resp) {
var id = request.params.id; var id = req.params.id;
for (let i=0; i < contacts.length; i++){
var contact = contacts[i];
if (contact._id == id){
contacts.splice(i, 1);
resp.status(200).end("Deleted");
return;
}
}
resp.status(404).end("Contact Not Found");
} }