This commit is contained in:
Arti Zirk 2017-05-11 13:16:38 +03:00
parent eab790d944
commit 8f4d4b9d06
2 changed files with 71 additions and 2 deletions

View File

@ -1,19 +1,61 @@
'use strict'; 'use strict';
const express = require('express'); const express = require('express');
const bodyParser = require('body-parser');
const TaskService = require('./task-service'); const TaskService = require('./task-service');
const dao = new TaskService(); const dao = new TaskService();
const app = express(); const app = express();
app.use(bodyParser.json()); // before request handlers
app.use(express.static('./'));
app.get('/api/tasks', getTasks); app.get('/api/tasks', getTasks);
app.get('/api/tasks/:id', getTask);
app.post('/api/tasks', addTask);
app.delete('/api/tasks/:id', deleteTask);
app.use(errorHandler); // after request handlers
app.listen(3000, () => console.log('Server is running on port 3000')); app.listen(3000, () => console.log('Server is running on port 3000'));
function getTasks(request, response) { function getTasks(request, response) {
response.set('Content-Type', 'application/json');
dao.getTasks() dao.getTasks()
.then(tasks => { .then(tasks => {
console.log(tasks); response.json(tasks);
response.end('ok');
}); });
} }
function getTask(request, response, next) {
var id = request.params.id;
dao.getTask(id)
.then(task => {
response.set('Content-Type', 'application/json');
response.json(task);
}).catch(next)
}
function addTask(request, response) {
var task = request.body
dao.addTask(task)
.then(task => {
response.set('Content-Type', 'application/json');
response.json(task);
}).catch(next)
}
function deleteTask(request, response) {
var id = request.params.id;
dao.deleteTask(id)
.then(task => {
response.set('Content-Type', 'application/json');
response.json(task);
}).catch(next)
}
function errorHandler(error, request, response, next) { // there must be 4 arguments
response.status(500).send('error: ' + error.toString());
}

View File

@ -15,6 +15,33 @@ class MemTaskService {
return Promise.resolve(this.clone(this.tasks)); return Promise.resolve(this.clone(this.tasks));
} }
getTask(id) {
for (let task of this.tasks) {
if (task._id === id) {
return Promise.resolve(this.clone(task));
}
}
return Promise.reject(`no task with id: ${id}`)
}
addTask(task) {
task._id = this.getNewId();
this.tasks.push(task);
return Promise.resolve(this.clone(task));
}
deleteTask(id) {
var task = null;
for (let i=0; i < this.tasks.length; i++) {
if (this.tasks[i]._id === id) {
this.tasks.splice(i, 1);
return Promise.resolve();
}
}
return Promise.reject(`no task with id: ${id}`)
}
clone(what) { clone(what) {
return JSON.parse(JSON.stringify(what)); return JSON.parse(JSON.stringify(what));
} }