From 611608869c2b3286fb2bf93183c89fd490f120bc Mon Sep 17 00:00:00 2001 From: Arti Zirk Date: Sat, 10 Jun 2017 22:26:00 +0300 Subject: [PATCH] Add server implementation --- ng1/server.js | 42 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/ng1/server.js b/ng1/server.js index 2921bb7..3a1f646 100644 --- a/ng1/server.js +++ b/ng1/server.js @@ -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"); }