From ea542fd1ea574aa2e9e868756f02a916516df37b Mon Sep 17 00:00:00 2001 From: Arti Zirk Date: Sun, 11 Jun 2017 00:24:59 +0300 Subject: [PATCH] hw3 first half done --- ng1/server.js | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/ng1/server.js b/ng1/server.js index 13c30eb..bd0b1ac 100644 --- a/ng1/server.js +++ b/ng1/server.js @@ -16,6 +16,7 @@ app.get('/api/contacts', getContacts); app.get('/api/contacts/:id', getContact); app.post('/api/contacts', addContact); app.put('/api/contacts/:id', changeContact); +app.post('/api/contacts/delete', deleteMultibleContact); app.delete('/api/contacts/:id', deleteContact); var contacts = [ @@ -64,14 +65,15 @@ function getContact(req, resp) { function addContact(req, resp) { var contact = req.body; - - contacts.push({ + var sanitizedContact = { "_id": ++lastContactId, "name": contact.name, "phone": contact.phone - }) + } - resp.status(201).end("Created"); + contacts.push(sanitizedContact) + + resp.status(200).json(sanitizedContact); } function changeContact(req, resp) { @@ -101,3 +103,35 @@ function deleteContact(req, resp) { } resp.status(404).end("Contact Not Found"); } + +function deleteMultibleContact(req, resp) { + var contactIds = req.body; + var invalidIds = []; + + while (true){ + let id = contactIds.pop() + if (!id){ + break; + } + for (let i=0; i < contacts.length; i++){ + var contact = contacts[i]; + if (contact._id == id){ + contacts.splice(i, 1); + id = null; + } + } + + if (id){ + invalidIds.push(id); + } + } + + if(invalidIds.length == 0){ + resp.status(200).end("Deleted"); + } else { + resp.status(404); + resp.json(invalidIds); + } + + +}