Add server implementation

This commit is contained in:
Arti Zirk 2017-06-10 22:26:00 +03:00
parent 85e046f2dd
commit 611608869c
1 changed files with 36 additions and 6 deletions

View File

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