i399exexpress/task-service.js
2017-05-09 15:42:06 +03:00

57 lines
1.1 KiB
JavaScript

'use strict';
const Task = require('./task');
class MemTaskService {
constructor() {
this.tasks = [
Task.withId('1', 'Task 1'),
Task.withId('2', 'Task 2')
];
}
clone(what) {
return JSON.parse(JSON.stringify(what));
}
getTasks() {
return Promise.resolve(this.clone(this.tasks));
}
getTask(id) {
let found = this.clone(this.tasks)
.filter(each => each._id === id)
.pop();
return found ? Promise.resolve(found) : Promise.reject('no task with id: ' + id);
}
saveTask(task) {
if (!task._id) {
task._id = this.getId();
this.tasks.push(task);
return Promise.resolve();
}
this.tasks = this.tasks
.map(each =>each._id === task._id ? task : each);
return Promise.resolve();
}
deleteTask(id) {
this.tasks = this.tasks
.filter(each => each._id !== id);
return Promise.resolve();
}
getId() {
return (Math.random() + 'A').substr(2);
}
}
module.exports = MemTaskService;