|
| 1 | +// Getting the Mongoose Model |
| 2 | +var ToDo = require('../models/todo.model') |
| 3 | + |
| 4 | +// Saving the context of this module inside the _the variable |
| 5 | +_this = this |
| 6 | + |
| 7 | +// Async function to get the To do List |
| 8 | +exports.getTodos = async function(query, page, limit) |
| 9 | +{ |
| 10 | + var options = { |
| 11 | + page, |
| 12 | + limit |
| 13 | + } |
| 14 | + // awaited promise, return todo list from the promise |
| 15 | + try { |
| 16 | + var todos = await ToDo.paginate(query, options) |
| 17 | + return todos; |
| 18 | + |
| 19 | + } catch(e) { |
| 20 | + throw Error('Error while Paginating Todos') |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +// Creating a new Mongoose Object |
| 25 | +exports.createTodo = async function(todo) |
| 26 | +{ |
| 27 | + var newTodo = new ToDo( { |
| 28 | + title: todo.title, |
| 29 | + description: todo.description, |
| 30 | + date: new Date(), |
| 31 | + status: todo.status |
| 32 | + }) |
| 33 | + // save and return the new todo |
| 34 | + try { |
| 35 | + var savedTodo = await newTodo.save() |
| 36 | + return savedTodo; |
| 37 | + } catch(e) { |
| 38 | + throw Error("Error while creating Todo") |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +exports.updateTodo = async function(todo){ |
| 43 | + var id = todo.id |
| 44 | + // Find the old Todo Object by the Id |
| 45 | + try { |
| 46 | + var oldTodo = await ToDo.findById(id); |
| 47 | + } catch(e) { |
| 48 | + throw Error("Error occured while finding the Todo") |
| 49 | + } |
| 50 | + // if no Todo exists return false |
| 51 | + if(!oldTodo){ |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + console.log(oldTodo) |
| 56 | + |
| 57 | + //Edit the Todo Object |
| 58 | + oldTodo.title = todo.title |
| 59 | + oldTodo.description = todo.description |
| 60 | + oldTodo.status = todo.status |
| 61 | + |
| 62 | + console.log(oldTodo) |
| 63 | + |
| 64 | + try { |
| 65 | + var savedTodo = await oldTodo.save() |
| 66 | + return savedTodo; |
| 67 | + } catch(e) { |
| 68 | + throw Error("Error occured while updating the Todo"); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +// Delete the Todo |
| 73 | +exports.deleteTodo = async function(id){ |
| 74 | + try { |
| 75 | + var deleted = await ToDo.remove({_id: id}) |
| 76 | + if(deleted.result.n === 0){ |
| 77 | + throw Error("Todo Could not be deleted") |
| 78 | + } |
| 79 | + return deleted |
| 80 | + } catch(e) { |
| 81 | + throw Error("Error Occured while Deleting the Todo") |
| 82 | + } |
| 83 | +} |
0 commit comments