homework/ng1/server.js

104 lines
2.3 KiB
JavaScript

'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.set('etag', false);
app.use(bodyParser.json()); // before request handlers
app.use(express.static('./'));
app.get('/api/contacts', getContacts);
app.get('/api/contacts/:id', getContact);
app.post('/api/contacts', addContact);
app.put('/api/contacts/:id', changeContact);
app.delete('/api/contacts/:id', deleteContact);
var contacts = [
{
"_id": 1,
"name": "Jack",
"phone": "123"
},
{
"_id": 2,
"name": "Jill",
"phone": "456"
},
{
"_id": 3,
"name": "Mary",
"phone": "789"
}
]
var lastContactId = 3;
app.use(errorHandler); // after request handlers
app.listen(3000, () => console.log('Server is running on port 3000'));
function errorHandler(error, request, response, next) { // there must be 4 arguments
response.status(500).send('error: ' + error.toString());
}
function getContacts(req, resp) {
resp.set('Content-Type', 'application/json');
resp.json(contacts);
}
function getContact(req, resp) {
var id = req.params.id;
resp.set('Content-Type', 'application/json');
for (let contact of contacts) {
if (contact._id == id) {
resp.json(contact);
return;
}
}
resp.status(404).end("Contact Not Found");
}
function addContact(req, resp) {
var contact = req.body;
contacts.push({
"_id": ++lastContactId,
"name": contact.name,
"phone": contact.phone
})
resp.status(201).end("Created");
}
function changeContact(req, resp) {
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 = 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");
}